vue手动实现sync
Vue 手动实现 .sync 修饰符
Vue 的 .sync 修饰符是语法糖,用于简化父子组件间的双向数据绑定。以下是手动实现 .sync 功能的两种方式:
通过 v-bind 和 v-on 实现
父组件通过 v-bind 传递 prop,同时监听子组件的 update:propName 事件:

<!-- 父组件 -->
<ChildComponent
:value="parentValue"
@update:value="parentValue = $event"
/>
子组件通过 $emit 触发更新:
// 子组件
this.$emit('update:value', newValue);
使用计算属性简化
子组件可以通过计算属性简化双向绑定的逻辑:

// 子组件
props: ['value'],
computed: {
innerValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('update:value', newValue);
}
}
}
动态 .sync 绑定
若需动态绑定多个属性,可以结合 v-bind 和对象展开:
<!-- 父组件 -->
<ChildComponent v-bind.sync="parentObject" />
子组件按需触发对应事件:
// 子组件
this.$emit('update:key1', newValue1);
this.$emit('update:key2', newValue2);
注意事项
- 手动实现时需确保事件名格式为
update:propName。 - 计算属性方式适用于需要复杂逻辑处理的场景。
- 动态绑定需注意对象属性的响应性。






