官方是没有提供 beforeChange 事件的,只能自己写一个
子组件(CustomRadioGroup)
< template>
< a- radio- group : model- value= "modelValue" @change= "onRadioChange" >
< a- radio v- for = "item in list" : value= "item.value" : key= "item" > { { item. label } } < / a- radio>
< / a- radio- group>
< / template>
< script setup>
import { ref } from 'vue'
const props = defineProps ( {
modelValue : Number,
list : {
type : Array,
default : ( ) => [ ] ,
} ,
beforeChange : Function,
} )
const emits = defineEmits ( [ 'change' , 'update:modelValue' ] )
const cacheValue = ref ( )
const onRadioChange = ( value ) => {
if ( props. beforeChange) {
props
. beforeChange ( )
. then ( ( ) => {
updateModelValue ( value)
} )
. catch ( ( ) => {
cacheValue. value = value
} )
} else {
updateModelValue ( value)
}
}
const updateModelValue = ( value ) => {
emits ( 'change' , value !== undefined ? value : cacheValue. value)
emits ( 'update:modelValue' , value !== undefined ? value : cacheValue. value)
}
defineExpose ( {
updateModelValue,
} )
< / script>
父组件
< template>
< a- form : module= "form" >
< a- form- item label= "性别" >
< CustomRadioGroup v- model= "form.sex" : list= "sexList" / >
< / a- form- item>
< a- form- item label= "学历" >
< CustomRadioGroup ref= "gradeRef" v- model= "form.grade" : list= "gradeList" : beforeChange= "beforeChange" / >
< / a- form- item>
< / a- form>
< a- modal title= "提示" v- model: visible= "confirmVisible" @ok= "handleOk" >
< div> 确定要切换吗?< / div>
< / a- modal>
< / template>
< script setup>
import CustomRadioGroup from './CustomRadioGroup.vue'
import { ref } from 'vue'
const sexList = [
{ label : '男' , value : 0 } ,
{ label : '女' , value : 1 } ,
]
const form = ref ( {
sex : 0 ,
grade : 1 ,
} )
const gradeList = [
{ label : '小学' , value : 0 } ,
{ label : '初中' , value : 1 } ,
{ label : '高中' , value : 2 } ,
]
const confirmVisible = ref ( false )
const beforeChange = ( ) => {
return new Promise ( ( resolve, reject ) => {
confirmVisible. value = true
reject ( )
} )
}
const gradeRef = ref ( )
const handleOk = ( ) => {
gradeRef. value. updateModelValue ( )
}
< / script>