Vue中不同的组件,即使不存在父子关系也可以相互通信,我们称为非父子关系通信;
我们需要借助一个空Vue实例,在不同的组件中,使用相同的Vue实例来发送/监听事件,达到数据通信的目的;

实例:
初始加载界面:

初始界面代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非父子关系组件之间的通信</title>
</head>
<body>
<div >
<my-component-a></my-component-a>
<my-component-b></my-component-b>
</div>
</body>
<template id="template-a">
<div>
<h1>my-component-a</h1>
<hr />
</div>
</template>
<template id="template-b">
<div>
<h2>my-component-b</h2>
<hr />
</div>
</template>
<script type="text/javascript" src="../js/vue.js" ></script>
<script type="text/javascript">
let comA = {
template : "#template-a",
}
let comB = {
template : "#template-b",
}
new Vue({
data : {
},
components : {
"my-component-a" : comA,
"my-component-b" : comB
}
}).$mount("div");
</script>
</html>
使用监听事件后:

添加的监听事件的代码:
let comA = { template : "#template-a", data(){ return { name:'perfect' } }, methods:{ sendData(){ vm.$emit('send-event-a',this.name); } } } let comB = { data(){ return{ nameB:'' } }, template : "#template-b", mounted(){ vm.$on('send-event-a',name=>{//监听数据 console.log(this); this.nameB=name; }) } } let vm=new Vue({ data:{ msg:'cool' } }); new Vue({ data : { },
调用事件部分:
<template id="template-a"> <div> <h1>my-component-a</h1> comA name:<span>{{name}}</span> <button @click="sendData">发送数据给comB</button> <hr /> </div> </template> <template id="template-b"> <div> <h2>my-component-b</h2> comB name:<span>{{nameB}}</span> <hr /> </div> </template>
最终代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>非父子关系组件之间的通信</title> 6 </head> 7 <body> 8 <div > 9 <my-component-a></my-component-a> 10 <my-component-b></my-component-b> 11 </div> 12 </body> 13 14 <template id="template-a"> 15 <div> 16 <h1>my-component-a</h1> 17 comA name:<span>{{name}}</span> 18 <button @click="sendData">发送数据给comB</button> 19 20 <hr /> 21 </div> 22 </template> 23 24 <template id="template-b"> 25 <div> 26 <h2>my-component-b</h2> 27 comB name:<span>{{nameB}}</span> 28 29 <hr /> 30 </div> 31 </template> 32 33 <script type="text/javascript" src="../js/vue.js" ></script> 34 <script type="text/javascript"> 35 36 let comA = { 37 template : "#template-a", 38 data(){ 39 return { 40 name:'perfect' 41 } 42 }, 43 methods:{ 44 45 sendData(){ 46 vm.$emit('send-event-a',this.name); 47 } 48 } 49 50 51 } 52 53 let comB = { 54 55 data(){ 56 return{ 57 nameB:'' 58 } 59 }, 60 template : "#template-b", 61 mounted(){ 62 63 vm.$on('send-event-a',name=>{//监听数据 64 console.log(this); 65 66 this.nameB=name; 67 }) 68 } 69 70 71 } 72 let vm=new Vue({ 73 74 data:{ 75 msg:'cool' 76 } 77 }); 78 79 80 new Vue({ 81 data : { 82 83 }, 84 components : { 85 "my-component-a" : comA, 86 "my-component-b" : comB 87 } 88 }).$mount("div"); 89 90 </script> 91 </html>