vue父子组件之间的通信
父组件与子组件交互
父组件给子组件传值
父组件传入数据:
<div>
<child-com :myParams="msg"></child-com>
</div>
data: {
msg: "我是参数值"
}
子组件接收:
props: {
myParams: {
type: String,
default: ""
}
}
父组件获取子组件属性和方法
父组件:
<div>
<child-com ref="child"></child-com>
<div @click="getD"></div>
</div>
methods: {
getD () {
this.$refs.child.msg;
this.$refs.child.show()
}
}
子组件:
data () {
return {
msg: "我是子组件数据"
}
},
methods:{
show () {
alert("haha")
}
}
子组件与父组件交互
子组件调用父组件的方法并传值
父组件:
<div>
<child-com @showF="show"></child-com>
</div>
methods:{
show:function(data){
console.log(data);
}
}
子组件:
methods:{
getD:function(){
this.$emit('showF','我是子组件传递的参数');
}
}
//子组件也可以通过$parent直接调用父组件的方法
this.$parent.show()
子组件与子组件交互
子组件与子组件交互需要新建一个空的vue实例作为中转层
var bus = new Vue();
子组件1 点击show方法调用另外一个子组件的change方法
methods:{
show:function(){
bus.$emit('change','传递参数');
}
}
子组件2
created:function(){
bus.$on('change',(data) => {
console.log(data);
})
}
下篇我们会介绍祖孙组件通信传值 provide 与 inject 以及 数据的响应式啦.....