u-grid.vue 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <view
  3. class="u-grid"
  4. ref='u-grid'
  5. :style="[gridStyle]"
  6. >
  7. <slot />
  8. </view>
  9. </template>
  10. <script>
  11. import props from './props.js';
  12. import mpMixin from '../../libs/mixin/mpMixin.js';
  13. import mixin from '../../libs/mixin/mixin.js';
  14. /**
  15. * grid 宫格布局
  16. * @description 宫格组件一般用于同时展示多个同类项目的场景,可以给宫格的项目设置徽标组件(badge),或者图标等,也可以扩展为左右滑动的轮播形式。
  17. * @tutorial https://ijry.github.io/uview-plus/components/grid.html
  18. * @property {String | Number} col 宫格的列数(默认 3 )
  19. * @property {Boolean} border 是否显示宫格的边框(默认 false )
  20. * @property {String} align 宫格对齐方式,表现为数量少的时候,靠左,居中,还是靠右 (默认 'left' )
  21. * @property {Object} customStyle 定义需要用到的外部样式
  22. * @event {Function} click 点击宫格触发
  23. * @example <u-grid :col="3" @click="click"></u-grid>
  24. */
  25. export default {
  26. name: 'u-grid',
  27. mixins: [mpMixin, mixin, props],
  28. data() {
  29. return {
  30. index: 0,
  31. width: 0
  32. }
  33. },
  34. watch: {
  35. // 当父组件需要子组件需要共享的参数发生了变化,手动通知子组件
  36. parentData() {
  37. if (this.children.length) {
  38. this.children.map(child => {
  39. // 判断子组件(u-radio)如果有updateParentData方法的话,就就执行(执行的结果是子组件重新从父组件拉取了最新的值)
  40. typeof(child.updateParentData) == 'function' && child.updateParentData();
  41. })
  42. }
  43. },
  44. },
  45. created() {
  46. // 如果将children定义在data中,在微信小程序会造成循环引用而报错
  47. this.children = []
  48. },
  49. computed: {
  50. // 计算父组件的值是否发生变化
  51. parentData() {
  52. return [this.hoverClass, this.col, this.size, this.border];
  53. },
  54. // 宫格对齐方式
  55. gridStyle() {
  56. let style = {};
  57. switch (this.align) {
  58. case 'left':
  59. style.justifyContent = 'flex-start';
  60. break;
  61. case 'center':
  62. style.justifyContent = 'center';
  63. break;
  64. case 'right':
  65. style.justifyContent = 'flex-end';
  66. break;
  67. default:
  68. style.justifyContent = 'flex-start';
  69. };
  70. return uni.$u.deepMerge(style, uni.$u.addStyle(this.customStyle));
  71. }
  72. },
  73. emits: ['click'], // 防止事件执行两次
  74. methods: {
  75. // 此方法由u-grid-item触发,用于在u-grid发出事件
  76. childClick(name) {
  77. this.$emit('click', name)
  78. }
  79. }
  80. };
  81. </script>
  82. <style lang="scss" scoped>
  83. @import "../../libs/css/components.scss";
  84. $u-grid-width:100% !default;
  85. .u-grid {
  86. /* #ifdef MP */
  87. width: $u-grid-width;
  88. position: relative;
  89. box-sizing: border-box;
  90. overflow: hidden;
  91. display: block;
  92. /* #endif */
  93. justify-content: center;
  94. @include flex;
  95. flex-wrap: wrap;
  96. align-items: center;
  97. }
  98. </style>