在某些狀況下,咱們可能須要對一個 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)
}
複製代碼