di-checkbox-list.vue 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <template>
  2. <u-checkbox-group ref='diCheckbox' class="di-checkbox-list" @change="handleChange" :active-color="activeColor">
  3. <u-checkbox class="di-checkbox-list__item" v-model="item.checked" v-for="(item, index) in checkboxList" :key="index"
  4. :name="item.value">
  5. {{ item.label }}
  6. </u-checkbox>
  7. </u-checkbox-group>
  8. </template>
  9. <script>
  10. /**
  11. * di-checkbox-list checkbox列表
  12. * @description checkbox列表组件,封装u-checkbox,适配form
  13. * @property {Array String} value 支持数组和字符串,修改后响应为,所以建议使用字符串
  14. * @property {String} active-color 激活时候的颜色
  15. * @property {Array} list 传入labelValue列表
  16. */
  17. export default {
  18. name: 'di-checkbox-list',
  19. data() {
  20. return {
  21. checkboxList: []
  22. }
  23. },
  24. methods: {
  25. /**
  26. * 改变选择
  27. * @param {Object} e
  28. */
  29. handleChange() {
  30. let values = [];
  31. this.checkboxList.map(val => {
  32. if(val.checked) values.push(val.value);
  33. })
  34. let valueStr = values.join(',')
  35. this.$emit('input', valueStr)
  36. this.$forceUpdate()
  37. // 由于头条小程序执行迟钝,故需要用几十毫秒的延时
  38. setTimeout(() => {
  39. this.$refs.diCheckbox.dispatch('u-form-item', 'on-form-change', valueStr);
  40. }, 60)
  41. },
  42. /**
  43. * 渲染成适配uview数据
  44. * @param {Object} list
  45. */
  46. __setCheckboxList(list) {
  47. let time = setTimeout(() => {
  48. clearTimeout(time)
  49. this.checkboxList = list.map(item => {
  50. item['checked'] = this.value2List.includes(item.value)
  51. return item
  52. })}, 0)
  53. }
  54. },
  55. computed: {
  56. /**
  57. * 将数据转化成list
  58. */
  59. value2List() {
  60. return this.value && typeof this.value === 'string' && this.value.split(',') || this.value || []
  61. }
  62. },
  63. watch: {
  64. list: {
  65. immediate: true,
  66. handler(value) {
  67. this.__setCheckboxList(value)
  68. }
  69. }
  70. },
  71. props: {
  72. value: {
  73. type: [Array, String],
  74. require: true
  75. },
  76. list: {
  77. type: Array,
  78. require: true
  79. },
  80. activeColor: {
  81. type: String,
  82. default: '#19be6b'
  83. }
  84. }
  85. }
  86. </script>
  87. <style lang="scss">
  88. </style>