<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>componentKnowledge-同级组件通信</title>
<script src="js/vue.js"></script>
</head>
<body>
<template id="aa">
<div>
I am aa component:{{msg}}
<input type="button" @click="send" value="SendTo-cc">
</div>
</template>
<template id="bb">
<div>
I am bb component:{{msg}}
<input type="button" @click="send" value="SendTo-cc">
</div>
</template>
<template id="cc">
<div>
<div>
I am cc component:{{msg}}/receive data:{{msg2}},{{msg3}}
</div>
</div>
</template>
<script>
window.onload=function(){
let Event=new Vue();
let aa={//定义组件
template:'#aa',
data(){
return {msg:'aa data'}
},
methods:{
send(){
Event.$emit('a-send',this.msg)
}
}
};
let bb={//定义组件
template:'#bb',
data(){
return {msg:'bb data'}
},
methods:{
send(){
Event.$emit('b-send',this.msg)
}
}
};
let cc={//定义组件
template:'#cc',
data(){
return {
msg:'cc data',
msg2:'',
msg3:''
}
},
mounted(){
Event.$on('a-send',(data)=>{this.msg2=data});
Event.$on('b-send',(data)=>{this.msg3=data});
}
};
let vm=new Vue({
el:'#app',
components:{//注册组件
aa,
bb,
cc
}
});
}
/*同级组件之间的通信关键总结:
1:新建一个空的root组件:let Event=new Vue();
其上有两个方法Event.$emit('a-fnName',data)/Event.$on('a-fnName',(data)=>{})
2:发送数据的组件:Event.$emit('a-fnName',data)写在组件的methods里,
3:接收数据的组件:Event.$on('a-fnName',(data)=>{}),注意函数格式必须写为箭头函数,不然this指向不是当前组件,一般写在钩子函数里(beforeCreate(){}/created(){}/beforeMount(){}/Mounted(){}/beforeUpdate(){}/updated(){}/beforeDestroy(){}/destroyed(){})
*/
</script>
<div id="app">
<!--使用组件-->
<aa></aa>
<bb></bb>
<cc></cc>
</div>
</body>
</html>