Vue's central event bus enables mutual communication between any components

Mount in the main.js file

Note: The central event bus implementation method can also be implemented in this way

  1. Create a new js file directly, create and export a vue instance in the file.
  2. Introduce this bus.js in the two components that need to communicate
  3. In the component that transfers data, the event name and the data to be transferred are sent through the vue instance method $emit. (send data component)
  4. The component that is passed the data listens to the event and receives the data through the vue instance method $on.

This method is described in the summary of communication methods between Vue components in this article, and there are several other communication methods in it.

This article mainly talks about the central event bus of vue, and the way to choose isCreate a vue instance directly and mount it to the prototype of vue (Vue.prototype), so that we can make method calls in any vue component. I think it is simpler and more straightforward to implement this way. The code in the main.js file is as follows:

// main.js
Vue.prototype.$bus = new Vue();

Initiate and listen to events in the corresponding components

// 发起事件的组件 this.$bus.$on
// 在对应代码处发起事件
// fn   为发起的事件名称,会被$bus.$on监听,可以自己定义名称(发起与监听的名称要一致)
// data 为需要传递的数据,能够在$bus.$on处获取
const data = 'abc'
this.$bus.$emit('fn', data)
// 响应事件的组件 this.$bus.$emit
// 先在mounted中进行注册监听
//(注意:注册监听的组件中,在组件销毁前记得通过$off注销对中央事件中线的监听)
// fn  为监听的事件名称,会由$emit发起,可以自己定义名称(发起与监听的名称要一致)
// foo 为响应事件的具体方法
methods: {
    
    
	foo(val) {
    
    
		console.log(val) // abc
	}
}
mounted() {
    
    
	this.$bus.$on('fn', this.foo)
}
beforeDestroy() {
    
    
  	this.$bus.$off("fn");
},

Notes (Central Event Bus does not take effect)

Because the central event bus is often used in cross-level components, sometimes friends will encounter the situation that the event is initiated, but the listening event does not respond.
The possible reason for this situation is: when the component that initiates the event initiates the event, the component that listens to the event has not been mounted or has not yet listened to the event. (Simply put, the listening event (on) must be before the event (emit) is initiated

Guess you like

Origin blog.csdn.net/IT_dabai/article/details/126946467