Detailed introduction to the use of Vue event bus (EventBus)

Preface

Very common Vue components include parent-child component communication and sibling component communication. The communication between parent and child components is very simple. The parent component will pass data down to the child component through props. When the child component has something to tell the parent component, it will tell the parent component through the $emit event. Today, let’s talk about how to communicate if there is no relationship between two pages that are introduced and introduced?

Detailed introduction to the use of Vue event bus (EventBus)

If our application does not need a library like Vuex to handle data communication between components, we can consider the event bus in Vue, namely EventBus , for communication.

Introduction to EventBus

EventBus is also called event bus. In Vue, EventBus can be used as a communication bridge concept. It is like all components share the same event center. You can register to send events or receive events to the center, so components can notify other components in parallel up and down, but that is too It is convenient, so if used carelessly, it will cause a "disaster" that is difficult to maintain. Therefore, a more complete Vuex is needed as a state management center to elevate the concept of notifications to the shared state level.

How to use EventBus

Detailed introduction to the use of Vue event bus (EventBus)

1. Initialization
First, you need to create the event bus and export it so that other modules can use or monitor it. We can handle this in two ways. Let’s look at the first one first, create a new .js file, such as event-bus.js

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
In fact, EventBus is a component that does not have a DOM. All it has is its instance method, so it is very lightweight.

Another way is to initialize EventBus directly in main.js in the project:

// main.js
Vue.prototype.$EventBus = new Vue()
Note that the EventBus initialized in this way is a global event bus. Let’s talk about the global event bus later.

Now that we have created the EventBus, all you need to do is load it in your component and call the same method just like you would in a parent-child component to pass messages to each other.

2.
Detailed introduction to the use of sending events Vue event bus (EventBus)

Suppose you have two Vue pages that need to communicate: A and B. Page A has a click event bound to the button and sends a message to notify page B.

<!-- A.vue -->
<template>
    <button @click="sendMsg()">-</button>
</template>

<script> 
import {
   
    
     EventBus } from "../event-bus.js";
export default {
   
    
    
  methods: {
   
    
    
    sendMsg() {
   
    
    
      EventBus.

Guess you like

Origin blog.csdn.net/sinat_52319736/article/details/127826608
Recommended