症状
Vue 记录 prop 被修改的警告,或子组件中的改动悄然回退。在 Vue 3 中 prop 对象是只读的,写入可能直接抛错。
诊断
在子组件中寻找赋值:
// child.vue — do not do this
props.count++;
count 归父组件所有,因此此处的任何写入都会在下一次渲染时被覆盖。
修复
发出事件,或保留本地副本:
// child.vue
const emit = defineEmits(['update:count']);
function increment() {
emit('update:count', props.count + 1);
}
// or an editable local buffer
const local = ref(props.count);
<Child v-model:count="count" />
验证
在子组件中执行自增;不再出现修改警告,父组件的值经事件得到更新。该值在重渲染后依然存在,确认数据流已由父组件掌控。