checkbox-group.vue 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <template>
  2. <component
  3. :is="tag"
  4. :id="groupId"
  5. :class="ns.b('group')"
  6. role="group"
  7. :aria-label="!isLabeledByFormItem ? label || 'checkbox-group' : undefined"
  8. :aria-labelledby="isLabeledByFormItem ? formItem?.labelId : undefined"
  9. >
  10. <slot />
  11. </component>
  12. </template>
  13. <script lang="ts" setup>
  14. import { computed, nextTick, provide, toRefs, watch } from 'vue'
  15. import { pick } from 'lodash-unified'
  16. import { UPDATE_MODEL_EVENT } from '@element-plus/constants'
  17. import { debugWarn } from '@element-plus/utils'
  18. import { useNamespace } from '@element-plus/hooks'
  19. import { useFormItem, useFormItemInputId } from '@element-plus/components/form'
  20. import { checkboxGroupEmits, checkboxGroupProps } from './checkbox-group'
  21. import { checkboxGroupContextKey } from './constants'
  22. import type { CheckboxGroupValueType } from './checkbox-group'
  23. defineOptions({
  24. name: 'ElCheckboxGroup',
  25. })
  26. const props = defineProps(checkboxGroupProps)
  27. const emit = defineEmits(checkboxGroupEmits)
  28. const ns = useNamespace('checkbox')
  29. const { formItem } = useFormItem()
  30. const { inputId: groupId, isLabeledByFormItem } = useFormItemInputId(props, {
  31. formItemContext: formItem,
  32. })
  33. const changeEvent = async (value: CheckboxGroupValueType) => {
  34. emit(UPDATE_MODEL_EVENT, value)
  35. await nextTick()
  36. emit('change', value)
  37. }
  38. const modelValue = computed({
  39. get() {
  40. return props.modelValue
  41. },
  42. set(val: CheckboxGroupValueType) {
  43. changeEvent(val)
  44. },
  45. })
  46. provide(checkboxGroupContextKey, {
  47. ...pick(toRefs(props), [
  48. 'size',
  49. 'min',
  50. 'max',
  51. 'disabled',
  52. 'validateEvent',
  53. 'fill',
  54. 'textColor',
  55. ]),
  56. modelValue,
  57. changeEvent,
  58. })
  59. watch(
  60. () => props.modelValue,
  61. () => {
  62. if (props.validateEvent) {
  63. formItem?.validate('change').catch((err) => debugWarn(err))
  64. }
  65. }
  66. )
  67. </script>