在main.js之中定义一个新的对象
//非父组件之间的通信使用事件车 来源于new Vue()
Vue.prototype.EmitEvent=new Vue();
左:
<template>
<div id="menuchild">
我是左端的子组件
<!--
非父子之间的传递数据
-->
<button @click="sendmsg">传递数据</button>
</div>
</template>
<script>
export default {
name: "menuchild",
methods: {
sendmsg() {
//发送数据发布自定义数据携带数据
this.EmitEvent.$emit("go-event", {
name: "张三",
age: 20
});
}
},
mounted() {
this.EmitEvent.$on("go-left", function(res) {
console.log(res);
});
}
};
</script>
右:
<template>
<div id="contentinfo">
我是右端的子组件
<button @click="sendto">发送左边的数据</button>
</div>
</template>
<script>
export default {
name: "contentinfo",
mounted() {
//该组件渲染完成之后 自动监听自定义事件
//new Vue对象
this.EmitEvent.$on("go-event", function(result) {
console.log(result);
});
},
methods: {
sendto() {
this.EmitEvent.$emit("go-left", "abcdef");
}
}
};
</script>
简易表达:
// main.js
const BUS = new Vue()
Vue.prototype.BUS = BUS
// A.vue
this.BUS.
e
m
i
t
(
′
c
h
a
n
g
e
S
i
d
e
b
a
r
′
)
/
/
c
h
a
n
g
e
S
i
d
e
b
a
r
和
emit('changeSidebar') // changeSidebar和
emit(′changeSidebar′)//changeSidebar和on处一致即可
// B.vue
mounted () {
this.BUS.$on('changeSidebar', () => {
this.isCollapse = !this.isCollapse
})
}