非父子组件可使用此方法,当然,不是说父子就不行(smile)
发车第一步,新建米奇巴士
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和StationB
接下来,直接开始组件通信,现在在StationA发车,带着信息,向公交车站B驶去
<template>
<div>
<div>這裡是stationA,向stationB发送消息</div>
<router-link to="/stationB">跳转</router-link>.
<!-- 通过router-link跳转到StationB,切换下视角,看看我们的信息是否通过小车到了B站 -->
</div>
</template>
<script>
export default {
name: "StationA",
beforeDestroy() {
// 在生命beforeDestroy生命周期中通过bus传递参数
this.$bus.$emit("bus", "this is A");
}
};
</script>
在StationB中,接受米奇巴士
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(hei);
});
}
};
来看看米奇bus的发车效果
以上效果存在问题,当我们多次跳转到StationB之后,后台打印次数会递增
解决重复发车的问题
原因在于每一次从A跳转到B都会新建一辆米奇巴士,现在我们在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>