u-grid.vue 2.7 KB

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