官方是没有提供 beforeChange 事件的,只能自己写一个
子组件(CustomRadioGroup)
javascript
<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'])
// radioGroup change事件
const cacheValue = ref()
const onRadioChange = (value) => {
// 父组件调用beforeChange方法
if (props.beforeChange) {
props
.beforeChange()
.then(() => {
// 1 走到 then 这里,直接更新父级数据
updateModelValue(value)
})
.catch(() => {
// 2 走到 catch 这里,说明父组件拦截住了,此时不能直接更新父组件数据,
// 留待后面父组件直接调用 updateModelValue 方法更新父组件数据,此处缓存住当前结果
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>
父组件
javascript
<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>