父子组件传值,父组件能够给子组件传值,可是子组件是不能修改组件提供的值,这里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>