在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。
所以官方推荐以update:my-prop-name 的模式触发事件取而代之。
一个很简单的小例子:(子组件单击按钮,显示或隐藏父组件的box)

<div id="app">
<costum-show :is-show.sync="show"></costum-show>
<div v-if="show">box</div>
</div>
<script>
Vue.component('costum-show', {
props:['isShow'],
template:`
<div>
<button @click="showHandle">显示/隐藏</button>
</div>
`,
methods: {
showHandle(){
this.$emit("update:isShow", !this.isShow);
}
}
})
var vm = new Vue({
el:'#app',
data:{
show: false
}
})
</script>
关键点:

网友评论