非父子组件之间的通信
A组件给B组件传数据:
A发送数据:
var Event_z = new Vue();
Event_z.$emit('data-a',this.a);
B接收数据:
mounted(){
Event_z.$on('data-a',a =>{
this.c=a;
})
必须是箭头函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
</head>
<body>
<div >
<l-a></l-a>
<l-b></l-b>
<l-c></l-c>
</div>
<template >
<div>
<h1>la: {{a}}</h1>
<button @click="atoc">点击发送</button>
</div>
</template>
<template >
<h2>lb: {{b}}</h2>
</template>
<template >
<h3>lc:{{c}}</h3>
</template>
</body>
<script>
var Event_z = new Vue();
new Vue({
el: '#app',
data:{
},
components:{
'l-a':{
template:'#la',
data:function () {
return {
a:"zheshi A"
}
},
methods:{
'atoc':function () {
Event_z.$emit('data-a',this.a);
console.log("发送成功")
}
}
},
'l-b':{
template: '#lb',
data:function () {
return {
b:"zheshi B"
}
}
},
'l-c':{
template: '#lc',
data:function () {
return {
c:"4"
}
},
mounted(){
Event_z.$on('data-a',a =>{
this.c=a;
console.log('接收成功')
})
}
}
}
})
</script>
</html>