Vue3 Options API中v-model变更未触发子组件可写计算属性问题
问题原因分析
- 子组件未接收对应Prop:父组件用
v-model:vModelTimeSeriesAgo绑定数据,但子组件的props里没声明vModelTimeSeriesAgo,导致子组件根本接收不到父组件传递的值,自然无法响应父组件的修改。 - 计算属性无限递归:子组件的计算属性
vModelTimeSeriesAgo的getter里返回this.vModelTimeSeriesAgo,这会不断调用自身的getter,逻辑完全错误,还会引发栈溢出,完全没关联到父组件传递的prop。 - 单选按钮绑定错误:单选按钮的
:value应该设为该选项的固定标识值,同时需要用checked绑定当前选中状态,否则无法同步父组件的选中值。 - 父组件响应式变量写法错误:Vue3 Options API中直接在
data里定义响应式变量即可,不需要混用ref再放到data中,这种写法会破坏响应性逻辑。
正确实现代码
子组件 RadioBtnTimeSeriesAgo.vue
<template> <cds-radio> <!-- 绑定该单选按钮的固定标识值,可根据实际业务调整 --> <input type="radio" :value="NDVIGuiConstants.CONST_RADIO_BUTTON_TIME_SERIES_AGO.value" :checked="vModelTimeSeriesAgo === NDVIGuiConstants.CONST_RADIO_BUTTON_TIME_SERIES_AGO.value" @input="$emit('update:vModelTimeSeriesAgo', $event.target.value)" @change="onTimeSeriesAgoChanged"/> <label>{{ tempTextTimeSeriesAgo }}</label> </cds-radio> </template> <script> import { NDVIGuiConstants } from './resources/NDVIComparisonGuiConstants.js'; export default { name: 'RadioBtnTimeSeriesAgo', data() { return {}; }, components: {}, props: { // 必须声明接收父组件传递的v-model绑定值 vModelTimeSeriesAgo: { type: String, required: true }, tempTextTimeSeriesAgo: { type: String, default: NDVIGuiConstants.CONST_RADIO_BUTTON_TIME_SERIES_AGO.description, }, }, emits: ['update:vModelTimeSeriesAgo'], methods: { onTimeSeriesAgoChanged() { console.log('onTimeSeriesAgoChanged'); }, }, }; </script>
父组件
<template> <button @click="onDigitizePolygon">修改选中值</button> <RadioBtnTimeSeriesAgo v-model:vModelTimeSeriesAgo="vModelTimeSeriesAgo"></RadioBtnTimeSeriesAgo> </template> <script> import RadioBtnTimeSeriesAgo from './RadioBtnTimeSeriesAgo.vue'; // 可根据实际业务调整常量值 const CONST_RADIO_BUTTON_TIME_SERIES_AGO = { value: 'ago' }; export default { components: { RadioBtnTimeSeriesAgo, }, data() { return { // 初始化选中值,对应单选按钮的value vModelTimeSeriesAgo: CONST_RADIO_BUTTON_TIME_SERIES_AGO.value } }, methods: { onDigitizePolygon() { // 模拟父组件修改v-model值,可替换为业务逻辑 this.vModelTimeSeriesAgo += '#'; }, }, }; </script>
关键说明
- 子组件必须声明对应的
prop接收父组件的v-model绑定值,这是双向绑定的基础。 - 单选按钮的核心逻辑:
value是选项的唯一标识,checked通过对比父组件传递的v-model值来控制选中状态。 - Options API中直接在
data里定义响应式变量即可,无需混用Composition API的ref。 - 如果一定要用可写计算属性封装,需确保getter返回prop值、setter触发emit事件,避免递归:
computed: { timeSeriesAgo: { get() { return this.vModelTimeSeriesAgo; }, set(value) { this.$emit('update:vModelTimeSeriesAgo', value); } } }
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

