Brother component communication of non parent-child component communication in Vue cli project

Keywords: Vue

First, draw on official documents
 Sometimes, two components of a non parent-child relationship need to communicate with each other. In a simple scenario, you can use an empty Vue instance as the event bus:
var bus = new Vue()
//Trigger events in component A
bus.$emit('id-selected', 1)
//Listen for events in the hook created by component B
bus.$on('id-selected', function (id) {
  // ...
})

How to use it? Don't talk about it. Go to the code directly
First, we need to add code in main.js, and then expose it to the outside world

var  bus = new Vue()

export default bus
Then? main.js That's it

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'

var  bus = new Vue()

export default bus

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
Prepare two sibling components. If there are two components, three.vue and four.vue
------------------------------------

three.vue component

<template>
    <div class="three">

        <button @click="change">Transfer events</button>

    </div>
</template>

<script>
import bus from '../main'

export default {
  props: {
    outdata: {
      type: String,
      default: ""
    }
  },
  data() {
    return {};
  },
  methods: {
    change() {
        // console.log(1)
      bus.$emit("outmes", "I am small.!");
    }
  }
};
</script>

four.vue component

<template>
    <div class="four">
        {{message}}
    </div>
</template>

<script>
import bus from '../main'

export default {
  data() {
    return {
      message: "I am component 4"
    };
  },
  //You need to listen to the event outlets from the bus in the lifetime mounted hook function 
  mounted() {
      let _this = this
    bus.$on("outmes", function(mes) {
      console.log(mes);
      _this.message = mes;
    });
  }
};
</script>

<style scoped>

</style>

Posted by varun_146100 on Fri, 27 Mar 2020 09:24:05 -0700