首页 > 其他 > 详细

13-Vue非父子组件之间的通信实战

时间:2019-07-02 22:28:25      阅读:127      评论:0      收藏:0      [点我收藏+]
直接贴代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../vue.js"></script>
<script>
window.onload = function () {
let Bus = new Vue();
let A = {
template:"#myA",
data(){
return{
name:"aaaa"
}
},
methods:{
send(){
Bus.$emit("data-a",this.name)
}
}
};
let B = {
template:"#myB",
data(){
return{
name:"bbbb"
}
},
methods:{
send(){
Bus.$emit("data-b",this.name)
}
}
};
let C = {
template:"#myC",
data(){
return{
name:"",
nameA:"",
nameB:"",
}
},
mounted() {
Bus.$on("data-a",function (name) {
//不能实现的原因:这里的this是Vue
this.name = name;
});
Bus.$on("data-a",name =>{
this.nameA = name
});
Bus.$on("data-b",name =>{
this.nameB = name
})
}
}
new Vue({
el:"#app",
components:{
"my-a":A,
"my-b":B,
"my-c":C
}
})

}
</script>
<template id="myA">
<div>
<h3>组件A{{name}}</h3>
<button @click="send">数据发送给C</button>
</div>
</template>
<template id="myB">
<div>
<h3>组件B{{name}}</h3>
<button @click="send">数据发送给C</button>
</div>
</template>
<template id="myC">
<div>
<h3>组件C接收的内容{{nameA}},{{nameB}}</h3>
</div>
</template>
</head>
<body>
<div id="app">
<my-a></my-a>
<my-b></my-b>
<my-c></my-c>
</div>

</body>
</html>
实现的效果:

技术分享图片技术分享图片技术分享图片

 

 

 

13-Vue非父子组件之间的通信实战

原文:https://www.cnblogs.com/Romantic-Blood/p/11123420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!