抛开父子组件的通讯,对于非父子组件通信,简单的数据交互,使用Bus是非常不错的。
遇到的坑有两个。
1.两个组件的信息交互代码写在哪个生命周期函数中,如果只是点击组件A标签触发函数,然后向界面B传递参数,是传递不到的。
2.小车次数越发越多,即一个信息重复发送了好几次
现在开始实现Bus,最快的方法,第一步,从main.js入手,直接在Vue原型上添加bus方法,简单有效
import Vue from 'vue'
import App from './App'
import router from './router'
//关键代码
Vue.prototype.$bus = new Vue();
//关键代码
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
接下来,直接开始组件通信,现在在StationA发车,带着信息,向公交车站B驶去(记得在router.js界面注册车站A和B)
<template>
<div>
<div>這裡是stationA,向stationB发送消息</div>
<router-link to="/stationB">跳转</router-link>.
<!-- 通过router-link跳转到StationB,切换下视角,看看我们的信息是否通过小车到了B站 -->
</div>
</template>
<script>
export default {
name: "StationA",
data() {
return {};
},
methods: {},
beforeDestroy() {
// 在生命beforeDestroy生命周期中通过bus传递参数
this.$bus.$emit("bus", "this is A");
},
mounted() {}
};
</script>
为什么要在生命周期beforeDestroy中传递我们的信息呢?Bus的坑之一就是这里。
因为要想让这个信息传递到B站,B站首先得有信息接收点,在A站beforeDestroy发车的时候,我们要在B站搭建好设备等小车开过来,即写在created里的 this.$bus. $on
created() {
this.$bus.$on("bus", hei => {
console.log(hei);
this.A_msg = hei;
});
},
来看StationB的代码
<template>
<div>
<div>这里是stationB</div>
<div>这是接收来的参数{{A_msg}}</div>
</div>
</template>
<script>
export default {
name: "StationB",
data() {
return {
A_msg: "",
};
},
created() {
this.$bus.$on("bus", hei => {
//接收小车的带来的信息,顺便打印一下
this.A_msg = hei;
});
console.log(this.A_msg);
}
};
最后一个坑,先来看看效果,点击跳转
来到了B站,哦 传达到了,后台也正常打印一次了
点击返回StationA我们再发一次车,跳转到StationB打印记录从1次直接涨到3次?
我们再发一次车试试
这次从3涨到了6,呈现一个规律+1,+2,+3递增的趋势,好像第一次发了一辆车,第二次发了两辆,第三次发了三辆,这么说问题,已经很清晰了。解决方法如下。
在StationA的生命周期created中添加代码
<template>
<div>
<div>這裡是stationA,向stationB发送消息</div>
<router-link to="/stationB">跳转</router-link>
</div>
</template>
<script>
// import Bus from "@/components/bus";
export default {
name: "StationA",
data() {
return {};
},
methods: {},
created() {
//新增代码看这里
this.$bus.$off("bus");
//新增代码看这里
},
beforeDestroy() {
// 在生命beforeDestroy生命周期中通过bus传递参数
this.$bus.$emit("bus", "this is A");
},
mounted() {}
};
</script>
这样就可以把之前存在的小车,取消掉,每次都只发一辆小车。