实例:点击按钮将组件A的"A数据"传到组件B的方框内
实现思路:根据官方文档的教程->使用一个空的 Vue 实例作为事件总线
代码展示
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script type="text/javascript" src="lib/vue.min.js" ></script>
<title>组件通讯</title>
<style>
.b{
width: 100px;
height: 100px;
border: 2px darkblue solid;
}
#app{
margin: 0 auto;
width: 100px;
text-align: center;
height: 600px;
}
</style>
</head>
<body>
<div id="app">
<mya></mya>
<myb></myb>
</div>
</body>
<template id="A">
<div>
<button @click="senddata">点击</button>
<h1>{{a}}</h1>
</div>
</template>
<template id="B">
<div>
<h1>{{b}}</h1>
<div class="b">
{{a}}
</div>
</div>
</template>
<script>
var bus = new Vue();
var vm=new Vue({
el:"#app",
components:{
"mya":{
template:"#A",
data:function(){
return {
a:"A数据"
}
},
methods:{
senddata:function(){
bus.$emit("a-msg",this.a);
}
}
},
"myb":{
template:"#B",
data:function(){
return {
b:"B数据",
a:""
}
},
mounted:function(){
var bthis=this;
bus.$on("a-msg",function(a){
bthis.a=a;
});
}
}
}
});
</script>
</html>
效果展示