vue props实现双向绑定
在 Vue 中实现 props 的双向绑定
Vue 的 props 默认是单向数据流,即父组件传递给子组件的数据不能直接在子组件中修改。但可以通过以下方法实现类似双向绑定的效果。
使用 v-model 语法糖
v-model 是 Vue 提供的语法糖,可以方便地实现父子组件之间的双向绑定。
父组件代码:
<template>
<ChildComponent v-model="parentValue" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentValue: 'initial value',
};
},
};
</script>
子组件代码:
<template>
<input :value="value" @input="$emit('input', $event.target.value)" />
</template>
<script>
export default {
props: ['value'],
};
</script>
使用 .sync 修饰符
Vue 2.x 提供了 .sync 修饰符,可以实现 props 的双向绑定。
父组件代码:
<template>
<ChildComponent :childProp.sync="parentValue" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentValue: 'initial value',
};
},
};
</script>
子组件代码:
<template>
<input :value="childProp" @input="$emit('update:childProp', $event.target.value)" />
</template>
<script>
export default {
props: ['childProp'],
};
</script>
手动实现双向绑定
如果不想使用 v-model 或 .sync,可以手动通过事件实现双向绑定。
父组件代码:
<template>
<ChildComponent :propValue="parentValue" @update="handleUpdate" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentValue: 'initial value',
};
},
methods: {
handleUpdate(newValue) {
this.parentValue = newValue;
},
},
};
</script>
子组件代码:
<template>
<input :value="propValue" @input="$emit('update', $event.target.value)" />
</template>
<script>
export default {
props: ['propValue'],
};
</script>
使用计算属性
在子组件中,可以通过计算属性实现 props 的双向绑定效果。
子组件代码:
<template>
<input v-model="computedValue" />
</template>
<script>
export default {
props: ['value'],
computed: {
computedValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('input', newValue);
},
},
},
};
</script>
注意事项
- 直接修改 props 会导致警告,应该通过事件通知父组件更新数据。
v-model默认使用value作为 prop 和input作为事件,可以通过model选项自定义。- Vue 3 中
.sync修饰符已被移除,推荐使用v-model或自定义事件实现双向绑定。







