Non-parent components can use this method, of course, not to say that the parent can’t (SMILE)

First step on the road, a new Mickey bus

import Vue from 'vue'
import App from './App'
import router from './router'
// Mickey Bus
Vue.prototype.$bus = new Vue();
// Mickey Bus
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
Copy the code

By default we have created two interfaces in the route, StationA and StationB

Next, start component communication straight away, now from StationA, with the message, heading for bus stop B

<template>
  <div>
    <div>This is stationA, sending a message to stationB</div>
    <router-link to="/stationB">jump</router-link>.
<! -- jump to StationB via router-link and switch the viewing Angle to see if our information arrived at StationB via car -->
  </div>
</template>
<script>
export default {
  name: "StationA".beforeDestroy() {
    // Pass parameters through bus in the life-beforeDestroy lifecycle
    this.$bus.$emit("bus"."this is A"); }};</script>
Copy the code

In StationB, accept mickey bus

 created() {
    this.$bus.$on("bus".hei= > {
      console.log(hei);
      this.A_msg = hei;
    });
  },
Copy the code

The complete StationB

<template>
  <div>
    <div>Here is the stationB</div>
    <div>This is the received parameter {{A_msg}}</div>
  </div>
 
</template>

<script>
export default {
  name: "StationB".data() {
    return {
      A_msg: ""}; },created() {
    this.$bus.$on("bus".hei= > {
    // Receive the information from the car, and print it
      this.A_msg = hei;
      console.log(hei); }); }};Copy the code

Let’s see how the Mickey Bus starts

There is a problem with the above effect, when we jump to StationB several times, the number of background printing will increase

Solve the problem of repeated departures

The reason is that every time you jump from A to B A new Mickey bus is created, and now we have added code to StationA’s lifecycle Created () to destroy every previous Mickey bus created

<template>
  <div>
    <div>This is stationA, sending a message to stationB</div>
    <router-link to="/stationB">jump</router-link>
  </div>
</template>

<script>
// import Bus from "@/components/bus";
export default {
  name: "StationA".data() {
    return {};
  },
  methods: {},
  created() {
  // Add code here
    this.$bus.$off("bus");
  // Add code here
  },
  beforeDestroy() {
    // Pass parameters through bus in the life-beforeDestroy lifecycle
    this.$bus.$emit("bus"."this is A");
  },
  mounted(){}};</script>
Copy the code