vue props实现双向绑定
在 Vue 中,props 默认是单向数据流(父组件 → 子组件),但可以通过以下方法实现类似双向绑定的效果:
使用 v-model 语法糖
父组件通过 v-model 传递数据,子组件通过 model 选项或直接使用 value 和 input 事件实现双向绑定。
父组件示例:
<template>
<ChildComponent v-model="parentData" />
</template>
<script>
export default {
data() {
return {
parentData: '初始值'
}
}
}
</script>
子组件示例:
<template>
<input :value="value" @input="$emit('input', $event.target.value)" />
</template>
<script>
export default {
props: ['value']
}
</script>
使用 .sync 修饰符
Vue 2.3+ 支持 .sync 修饰符,通过特定的事件名实现双向绑定。
父组件示例:
<template>
<ChildComponent :title.sync="parentTitle" />
</template>
子组件示例:
<template>
<input :value="title" @input="$emit('update:title', $event.target.value)" />
</template>
<script>
export default {
props: ['title']
}
</script>
手动实现事件监听
通过显式定义 props 和自定义事件实现双向绑定。
父组件示例:
<template>
<ChildComponent :data="parentData" @update="parentData = $event" />
</template>
子组件示例:
<template>
<input :value="data" @input="$emit('update', $event.target.value)" />
</template>
<script>
export default {
props: ['data']
}
</script>
注意事项
- 直接修改
props会导致警告,应始终通过事件通知父组件更新。 - 双向绑定可能增加数据流向的复杂性,建议在必要时使用。
- Vue 3 中
v-model和.sync的行为有所调整,需注意版本差异。
以上方法均能实现类似双向绑定的效果,但本质仍是单向数据流+事件触发的组合。







