Communication between Vue brothers---EventBus


1. What is EventBus?

EventBus is called an event bus, similar to Vuex.

In essence, EventBus is a component that does not have a DOM. All it has is its instance method.

The principle of eventBus is to create an empty Vue instance, and then mount communication events on it. When responding to an event, this Vue instance (component) can be considered to be the parent component of all components. When an event is triggered, this Vue instance can be considered to be subcomponents of all components

2. Usage steps

1.Initialization

There are two ways to initialize

1-1. bus.js is loaded on demand

import Vue from 'vue';
let bus = new Vue();
export default bus;

1-2. Introduce globally in main.js

Vue.prototype.$bus = new Vue();

2.Send data

<template>
    <div>
        <div>
            <el-button type="primary" @click="sendMsg">发送数据</el-button>
        </div>
    </div>
</template>

<script>
import bus from '../utils/bus'
export default {
    
    
    data() {
    
    
        return {
    
    
            testBus:'你好呀,bus!',
        }
    },
    methods: {
    
          
        sendMsg() {
    
    
            //通过触发$emit函数进行触发,发送数据
            //第一个参数为事件名称
            //第二个参数为传送的数据 注意要用this指定要发送的数据 
            bus.$emit('share', this.testBus) //使用第一种
      //      this.$bus.$emit('share', this.testBus) //使用第二种
        }
}
</script>

3.Receive data

<template>
    <div>{
    
    {
    
    receiveBus}}</div>
</template>

<script>
import bus from '../utils/bus'
export default {
    
    
    data() {
    
    
        return {
    
    
            receiveBus :'',
        }
    },
    created() {
    
    
    //使用第一种
     bus.$on('share', val => {
    
    
         this.receiveBus = val
     })  
     //使用第二种引入方式
//      this.$bus.$on('share', val => {
    
    
  //       this.receiveBus = val
    // })
   },
}
</script>

Insert image description here

Guess you like

Origin blog.csdn.net/2201_75499330/article/details/131952188