fs-checkbox-group.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <template>
  2. <view class="fs-checkbox-group" :class="{inline}">
  3. <slot></slot>
  4. </view>
  5. </template>
  6. <script setup>
  7. import { provide, reactive, watch, toRefs } from 'vue'
  8. const props = defineProps({
  9. max: {
  10. type: Number,
  11. default: -1
  12. },
  13. justify: String,
  14. reverse: Boolean,
  15. inline: Boolean,
  16. checkedColor: String,
  17. checkedColorType: {
  18. type: String,
  19. default: 'primary',
  20. validator(value) {
  21. return ['primary', 'success', 'info', 'warning', 'danger'].includes(value)
  22. }
  23. },
  24. radius: Boolean,
  25. round: Boolean,
  26. size: {
  27. type: String,
  28. validator(value) {
  29. return ['mini', 'small', 'medium'].includes(value)
  30. }
  31. },
  32. modelValue: {
  33. type: Array,
  34. default() {
  35. return []
  36. }
  37. }
  38. })
  39. const emits = defineEmits(['update:modelValue','change'])
  40. const state = reactive({
  41. selectedValue: props.modelValue,
  42. children: []
  43. })
  44. watch(() => props.modelValue, val => {
  45. state.selectedValue = val
  46. })
  47. const checkStrategy = value => {
  48. state.children.forEach(item => {
  49. if (typeof item.value === 'object') {
  50. item.selected = state.selectedValue.filter(selected => selected.id === item.value.id).length > 0
  51. } else{
  52. item.selected = state.selectedValue.indexOf(item.value) > -1
  53. }
  54. })
  55. }
  56. const updateChildren = child => {
  57. state.children.push(child)
  58. checkStrategy()
  59. }
  60. const updateValue = value => {
  61. let index = -1
  62. if (typeof value === 'object') {
  63. state.selectedValue.forEach((item, key) => {
  64. if(item.id === value.id) {
  65. index = key
  66. }
  67. })
  68. } else{
  69. index = state.selectedValue.indexOf(value)
  70. }
  71. if (state.selectedValue.length < props.max || props.max === -1) {
  72. if (index === -1) {
  73. state.selectedValue.push(value)
  74. } else {
  75. state.selectedValue.splice(index, 1)
  76. }
  77. } else {
  78. index > -1 && state.selectedValue.splice(index, 1)
  79. }
  80. }
  81. watch(() => state.selectedValue, val => {
  82. checkStrategy()
  83. emits('update:modelValue', val)
  84. emits('change', val)
  85. },{deep: true})
  86. provide('checkboxGroup', {
  87. ...toRefs(props),
  88. updateChildren,
  89. updateValue
  90. })
  91. </script>
  92. <style lang="scss" scoped>
  93. .fs-checkbox-group{
  94. &.inline{
  95. display: flex;
  96. flex-wrap: wrap;
  97. }
  98. }
  99. </style>