fs-checkbox-group.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. item.selected = state.selectedValue.indexOf(item.value) > -1
  50. })
  51. }
  52. const updateChildren = child => {
  53. state.children.push(child)
  54. checkStrategy()
  55. }
  56. const updateValue = value => {
  57. const index = state.selectedValue.indexOf(value)
  58. if (state.selectedValue.length < props.max || props.max === -1) {
  59. if (index === -1) {
  60. state.selectedValue.push(value)
  61. } else {
  62. state.selectedValue.splice(index, 1)
  63. }
  64. } else {
  65. index > -1 && state.selectedValue.splice(index, 1)
  66. }
  67. }
  68. watch(() => state.selectedValue, val => {
  69. checkStrategy()
  70. emits('update:modelValue', val)
  71. emits('change', val)
  72. },{deep: true})
  73. provide('checkboxGroup', {
  74. ...toRefs(props),
  75. updateChildren,
  76. updateValue
  77. })
  78. </script>
  79. <style lang="scss" scoped>
  80. .fs-checkbox-group{
  81. &.inline{
  82. display: flex;
  83. flex-wrap: wrap;
  84. }
  85. }
  86. </style>