版权声明:本文为QQ帝国原创博客,转载请附上链接,谢谢。 https://blog.csdn.net/QQ_Empire/article/details/89301527
问题代码:
父组件代码
<template>
<div class="parent">
<button @click="showPanel">显示弹窗</button>
<v-popup v-show="panelShow" :panelShow="panelShow"></v-popup>
</div>
</template>
<script>
export default {
data() {
return {
panelShow: false
}
},
methods: {
showPanel() {
this.panelShow = true;
}
},
components: {
'v-popup': Popup
}
}
</script>
子组件
<template>
<div class="popup">
<button @click="hidePanel">关闭弹窗</button>
</div>
</template>
<script>
export default {
props:{
panelShow: {
type: Boolean
}
},
methods: {
hidePanel() {
//this.panelShow = false; //错误方法
}
}
}
</script>
修改后代码:
用 .sync 来实现一个双向绑定,具体实现如下:
<template>
<div class="parent">
<button @click="showPanel">显示弹窗</button>
// 把显示隐藏扔给子组件处理,即 v-show 放到子组件上
<v-popup :panelShow.sync="panelShow"></v-popup>
</div>
</template>
<script>
export default {
data() {
return {
panelShow: false
}
},
methods: {
showPanel() {
this.panelShow = true; //显示
}
},
components: {
'v-popup': Popup
}
}
</script>
子组件
<template>
// 在这里控制显示隐藏
<div v-show="panelShow" class="popup">
<button @click="hidePanel">关闭弹窗</button>
</div>
</template>
<script>
export default {
props:{
panelShow: {
type: Boolean
}
},
methods: {
hidePanel() {
// 下面的语句配合开头写的 .sync 就会更新父组件中的 panelShow 变量
this.$emit('update:panelShow', false) //弹框隐藏,意为panelShow为false
}
}
}
</script>