vue 3 中 @update:modelvalue 是实现 v-model 双向绑定的核心机制,子组件需声明 modelvalue prop 和 update:modelvalue 事件,通过 emit 触发更新,父组件直接使用 v-model 即可。

在 Vue 3 中,@update:modelValue 是实现自定义组件双向绑定(v-model)的核心机制,它替代了 Vue 2 的 .sync 和 v-model 修饰符的旧写法。本质是:父组件用 v-model,子组件内部通过 emit('update:modelValue', newValue) 触发更新,Vue 自动将它映射为 @update:modelValue 监听。
✅ 正确声明 props 和 emit
子组件需显式声明接收 modelValue prop,并定义 update:modelValue 事件(推荐使用 defineEmits):
// Child.vue(组合式 API)
<script setup>
const props = defineProps({
modelValue: {
type: [String, Number, Boolean],
default: ''
}
})
<p>const emit = defineEmits(['update:modelValue'])<p>// 当内部值变化时,触发更新
const handleChange = (value) => {
emit('update:modelValue', value)
}
</script><p><template><input :value="props.modelValue"></template></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill1140" title="Vue"><img
src="https://img.php.cn/upload/skill/000/000/081/178797612947731.jpg" alt="Vue" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill1140" title="Vue" class="overflowclass">Vue</a>
<p class="overflowclass">避免 Vue 常见错误——响应式陷阱、ref 与 reactive 区别、计算属性时机及 Composition API 陷阱。</p>
</div>
<a rel="nofollow" href="/xiazai/skill1140" title="Vue" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>✅ 父组件用法:直接 v-model 即可
无需手动写 @update:modelValue,Vue 会自动展开:
<!-- Parent.vue --> <child v-model="searchText"></child><!-- 等价于 --><child :model-value="searchText"></child>
✅ 支持自定义 v-model 名称(可选)
若想用 v-model:xxx(如 v-model:count),需同时指定 prop 名和事件名:
// Child.vue
defineProps({
count: Number // 注意:prop 名变为 'count'
})
const emit = defineEmits(['update:count'])
<p>// 使用时
emit('update:count', newCount)</p><p>// Parent.vue
<child v-model:count="totalCount"></child></p>✅ 注意事项
-
prop 名必须是
modelValue(默认 v-model)或与修饰符一致(如count对应v-model:count) -
事件名必须是
update:xxx,且 xxx 与 prop 名严格对应 - 不要在子组件内直接修改
props.modelValue—— 应始终通过emit通知父组件更新 - 使用
v-model时,父组件绑定的变量必须是响应式(如ref或reactive字段)
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!









