父子組件傳值,父組件能夠給子組件傳值,可是子組件是不能修改組件提供的值,這裏vue提供了sync修飾符,之前父組件點擊子組件顯示,子組件關閉按鈕,父組件再點擊子組件就沒法讓子組件顯示。由於子組件點擊關閉時候v-show屬性爲false,父組件只能在子組件中設置ref,經過ref獲取到子組件的v-show屬性,而後在點擊事件下更改子組件的v-show屬性爲true,這樣點擊父組件點擊子組件,子組件就能顯示了。vue
如今能夠經過sync修飾符子組件能夠更改父組件的v-show屬性。this
Child:spa
<template>
<div>
<div v-if="show">
<p>默認初始值是{{show}},因此是顯示的</p>
<button @click.stop="closeDiv">關閉</button>
</div>
</div>
</template>
<script>
export default {
name: "Child",
props:['show'],
methods:{
closeDiv() {
this.$emit('update:show', false); //觸發 input 事件,並傳入新值
}
}
}
</script>
parents:
<template>
<div class="hello">
<Child :show.sync="valueChild"></Child>
<button @click="changeValue">toggle</button>
</div>
</template>
會拓展爲:
<div class="hello">
<Child :show="valueChild" @change='update: show="val=valueChild=val'></Clild>
當子組件須要更新show的值時,它須要顯式地觸發一個更新事件:this.$emite('update:show',newValue)
</Child>
<button @click="changeValue">toggle</button>
</div>
<script>
import Child from '../components/Child'
export default {
name: 'HelloWorld',
components:{
Child
},
data () {
return {
msg: 'Welcome to Your Vue.js App',
valueChild:true,
}
},
methods:{
changeValue(){
this.valueChild = !this.valueChild
}
}
}
</script>