在某些状况下,咱们可能须要对一个 prop 进行“双向绑定”。javascript
简单的方法是 子组件向父组件发送一个事件,父组件监听该事件,而后更新propjava
父组件:web
<template>
<div id="FatherCom"> <h4>我是父组件</h4> <div v-show="show">能看得见我吗?</div> <hr> <ChildCom :show="show" @update:show="update_show"/> </div> </template>
<script> import ChildCom from './ChildCom' export default { name: 'FatherCom', components: { ChildCom }, data() { return { show: true } }, methods: { update_show(val) { this.show = val } } } </script>
<style scoped> </style>
复制代码
子组件:markdown
<template>
<div id="ChildCom"> <h4>我是子组件</h4> <button @click="handle" >显示/隐藏</button> </div>
</template>
<script> export default { name: 'ChildCom', props:['show'], methods:{ handle(){ this.$emit('update:show',!this.show) } } } </script>
<style scoped> </style>
复制代码
可是以上父组件定义 自定义事件的步骤过于繁琐了。ui
能够经过 .sync修饰符简化父组件的代码:this
update:myPropName
方式命名(尤雨溪要求的),:show:show
加上.sync修饰符, 即 :show.sync:show
这样设置父组件就再也不须要单独再去绑定@update:show事件了 。url
修改代码:spa
<template>
<div id="FatherCom"> <h4>我是父组件</h4> <div v-show="show">能看得见我吗?</div> <hr> <!--<ChildCom :show="show" @update:show="update_show"/>--> <ChildCom :show.sync="show" /> </div> </template>
复制代码
handle(){
// 这里要求用 `update:myPropName` 方式命名
this.$emit('update:show',!this.show)
}
复制代码