父子组件值传递和数据传递
昨天程序中用到的,以前没搞懂 现学会的 做个笔记
背景:
需求:
两个页面共用一个自定义的Popup 弹出层 组件。
问题:
Popup 本身自带一个隐藏显示的属性。点击关闭后属性值变成了false,父组件无法第二次调起使用。
html
## 子组件
<u-popup v-model="show" mode="bottom" height="60%" @close="close">
//子组件代码省略 就是一个从通信录选人,然后输入留言的功能
</u-popup
## 父组件使用
<pop-custom v-show="show" :info="info" @itemclick="confim" @closePop="closePop" ref="child"></pop-custom>
script
## 父组件的方法
handleClick(item) { //调起子组件
this.show = true;
console.log(this.$refs.child);
this.$refs.child.open(); //调用子组件的open()方法把子组件本身设为true可见 避免第二次调用失败问题
},
closePop() {
this.show = false; //隐藏子组件的方法
},
confim(option) {
console.log(option); //子组件传递回来的数据(子组件中的this.rdata)
//本身业务逻辑
}
## 子组件的方法
close() {
this.$emit('closePop', this.show); //实际是调用父组件的方法
},
open() {
this.show = true;
},
confim() {
//一些条件判断
//向上传递 调用父组件的方法 并把数据传给父组件
this.$emit('itemclick', this.rdata);
},