vue手动实现sync
实现 Vue 的 .sync 修饰符
Vue 的 .sync 修饰符用于实现父子组件之间的双向绑定。手动实现 .sync 可以通过以下方式完成。
父组件传递 prop 和事件
在父组件中,通过 v-bind 传递 prop,并通过 v-on 监听子组件触发的事件。事件名格式为 update:propName。
<template>
<ChildComponent
:value="parentValue"
@update:value="parentValue = $event"
/>
</template>
<script>
export default {
data() {
return {
parentValue: '初始值'
}
}
}
</script>
子组件触发更新事件
在子组件中,通过 $emit 触发 update:propName 事件来更新父组件的值。
<template>
<input
:value="value"
@input="$emit('update:value', $event.target.value)"
/>
</template>
<script>
export default {
props: ['value']
}
</script>
使用计算属性简化
如果需要更灵活地处理数据,可以在子组件中使用计算属性。
<template>
<input v-model="internalValue" />
</template>
<script>
export default {
props: ['value'],
computed: {
internalValue: {
get() {
return this.value
},
set(val) {
this.$emit('update:value', val)
}
}
}
}
</script>
多 prop 的双向绑定
如果有多个 prop 需要双向绑定,可以重复上述模式。

<template>
<ChildComponent
:value1="parentValue1"
@update:value1="parentValue1 = $event"
:value2="parentValue2"
@update:value2="parentValue2 = $event"
/>
</template>
手动实现 .sync 的关键在于理解父子组件之间的 prop 传递和事件通信机制。通过这种方式可以实现灵活的双向数据绑定。






