MyRadioButtonGroup.vue 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <template>
  2. <div class="my-radio-group">
  3. <slot></slot>
  4. </div>
  5. </template>
  6. <script setup>
  7. import { ref, provide } from 'vue'
  8. const props = defineProps({
  9. modelValue: [String, Number, Boolean, Object, Array, null]
  10. })
  11. const emit = defineEmits(['update:modelValue'])
  12. // 使用 ref 来包装 value 以确保响应性
  13. const valueRef = ref(props.modelValue)
  14. // 监听 group.value 的变化
  15. watch(
  16. () => valueRef.value,
  17. (newVal, oldVal) => {
  18. console.log('选择的右边胡麻:', newVal, oldVal)
  19. }
  20. )
  21. // 提供给子组件的上下文
  22. const groupContext = {
  23. value: valueRef,
  24. changeValue: (value) => {
  25. console.log('点击了吗父布局', props.modelValue)
  26. valueRef.value = value // 修改 ref 的值
  27. // 改为通过 emit 更新值
  28. emit('update:modelValue', value)
  29. emit('change', value)
  30. }
  31. }
  32. provide('MyRadioGroupContext', groupContext)
  33. const setClean = (text) => {
  34. valueRef.value = text
  35. }
  36. defineExpose({
  37. setClean
  38. })
  39. </script>
  40. <style scoped>
  41. .my-radio-group {
  42. display: flex;
  43. flex-wrap: wrap;
  44. }
  45. </style>