Vue 的文档关于组件基础一节中,说明了通过 prop 向组件传递数据。但是有的时候prop需要进行“双向绑定”。目的是当子组件修改了prop的值时,可以使这个变化同步到父组件。
参考EventBus,可以通过触发事件和监听事件来达到此目的。但是 Vue 有 .sync修饰符也可以使 prop 的数据变化同步到组件。
以下是两个组件的代码示例:父组件通过showValue控制显示子组件;子组件点击“关闭”,showValue被子组件传递的新值变成false。
子组件示例代码:
<template>
<div class="child" v-show="show">
这是子组件
<button @click="CloseDiv">关闭</button>
</div>
</template>
<script>
export default {
props: ["show"],
methods:{
CloseDiv(){
this.$emit('update:show',false)
// 子组件触发事件 update:show ,传递参数值 false
}
}
};
</script>
<style>
.child {
border: 3px solid green;
}
</style>
父组件代码:
<template>
<div class="father">
这是父组件
<button @click="changeValue">显示子组件</button>
<hr>
<Child :show="showValue" v-on:update:show="showValue=$event" />
// 监听 update:show 事件,showValue值变成false
</div>
</template>
<script>
import Child from './Child.vue';
export default {
components: {Child},
data(){
return {showValue: true}
} ,
methods:{
changeValue(){
this.showValue=true
}
}
};
</script>
<style>
.father{
border: 5px solid red;
}
</style>
初始页面效果:
按下关闭键后:
子组件通过
this.$emit触发事件update:show,父组件通过 v-on:update:show="showValue=$event"监听事件并传递新值($event)。
其中父组件的:
<Child :show="showValue" v-on:update:show="showValue=$event" />可缩写,即使用 .sync修饰符。
<Child :show.sync="showValue" />等价于
<Child :show="showValue" v-on:update:show="showValue=$event" />
总结:
.sync修饰符——当子组件修改了prop的值时,可以使这个变化同步到父组件。- Vue中推荐被触发、监听的事件命名为
update:名字。 .sync修饰符的v-bind不能和表达式一起使用 (例如v-bind:title.sync=”doc.title + ‘!’”是无效的)。 参考文档: