In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use eventemitter2 to achieve Vue component communication" related knowledge, the editor through the actual case to show you the operation process, the operation method is simple and fast, practical, I hope that this "how to use eventemitter2 to achieve Vue component communication" article can help you solve the problem.
Overview
When there is no parent-child relationship between the two components, the use of Vue standard props values and emit trigger events can not solve the problem of communication between them. The most recent project uses eventemitter2 to communicate between unrelated components. This article shares my summary and experience of using eventemitter2.
You can see the eventemitter2 introduction to eventemitter2's npm documents. It is the event interface provided by node.js. The installation is as follows
Npm install-save eventemitter2
The EventEmitter2 property of the module is a constructor that generates an instance of eventemitter2. The instance defines the methods for binding, triggering, and removing events. The example methods involved in this article are on,off,emit,removeAllListeners, more methods, you can go to the npm document to learn by yourself.
Like other event handling mechanisms, eventemitter2 event handling must consist of three parts:
Bind event = "trigger event =" remove event
This sharing focuses on the use of eventemitter2 in vue projects:
Method 1: encapsulate the instance, event name, bind event method and remove event method with class modular programming
Method 2: add event instances globally combined with vue plug-in development
Method 1: combine class
Development steps:
Add module event_confg.js to store eventEmitter2 instances and event names
Add module event_manager.js, encapsulate methods for binding events to instances and methods for removing events
Follow the steps of binding event = "trigger event =" to remove the event, using eventeitter2
Step 1: create an event_confg.js
Var EventEmitter2 = require ('eventemitter2') .EventEmitter2;// emiter is defined as eventemitter2 instance, and config is defined as event name const eventConfig = {} eventConfig.emitter = new EventEmitter2 () eventConfig.config = {"CHECK_CHANGES": "checkChanges" / / more event names, add} export default eventConfig here
Step 2: create an event_manager.js
This module creates a class, and after passing in the eventemitter2 instance, it encapsulates the methods of adding and removing events from the instance.
Here the on,off method is used to bind and remove events, respectively.
Export default class {constructor (evtInst) {this.evtInst = evtInst this.listeners = {} / / {eventName: [callback1,callback2...]}} / / binds the callback of the event name evtName to callback, while saving the event name and callback to listeners Facilitate the subsequent removal of events using addListener (evtName, callback) {this.evtInst.on (evtName, callback) if (! this.listeners [evtName]) {this.listeners [evtName] = [callback]} else {this.listeners[ evtName] .push (callback)} removeListeners () {Object.keys (this.listeners) .forEach (evtName = > {this.lis teners[ evtName] .forEach ((callback, index) = > {this.evtInst.off (evtName)) Callback)}}
Step 3: use eventemitter2 in components
Bind event
Multiple event callbacks can be bound to the same event name. When events are triggered, callback functions with the same name will be executed sequentially.
Import EventManager from "@ / utils/event_manager.js" import eventConfig from "@ / utils/event_config.js"... / / initialize the event_manager instance this.evtManagerInst = new EventManager (eventConfig.emitter) / / bind the event this.evtManagerInst.addListener (eventConfig.config.CHECK_CHANGES, obj = > {this.value = Object.is (NaN,parseInt (obj.value))}) this.evtManagerInst.addListener (eventConfig.config.CHECK_CHANGES) with the instance's addListener method Obj = > {console.log ("the second event is also triggered!" , obj)})
Trigger event
Event triggers and callbacks are executed synchronously. After the event is triggered in the following way, the procedure to be executed is:
Print ready to trigger! = "execute callback =" execute $message pop-up box
Import eventConfig from "@ / utils/event_config.js"... / / parameters passed to the event callback function let obj = {value: val, type: ", msg:"} / / trigger event console.log ("ready to trigger!") Processing this.$message after eventConfig.emitter.emit (eventConfig.config.CHECK_CHANGES, obj) / / event is triggered ({type: obj.type, message: obj.msg})
Remove event
Remove events in beforeRouteLeave or beforeDestory
If you are using beforeRouteLeave, pay attention to calling its next function and let the route continue.
BeforeDestroy () {this.evtManagerInst.removeListeners ()}
Method 2: develop with Vue plug-in
The idea is to add a global eventemitter2 object as a property to the top-level Vue object.
Development steps:
Use install to create an emitter.js plug-in in which you add global attributes to Vue
Using the global Vue.use () method, using the plug-in
Follow the steps of binding event = "trigger event =" to remove the event, using eventeitter2
Step 1: create a global variable
Add the global attribute $emit_inst to store the instance; add the global $emit_name to store the event name
Var EventEmitter2 = require ('eventemitter2') .EventEmitter2;// event name, instance const emitter = {} / / create instance, define event name emitter.install = function (Vue) {Vue.prototype.$emit_inst = new EventEmitter2 () Vue.prototype.$emit_name = {"CHECK_TYPE_TWO": "checkTypeTwo", "ANOTHER_EVENT": "anotherEvt" / / continue to add instance name}} export default emitter
Step 2: use plug-ins
In main.js, before the new Vue () command creates the instance, call the Vue.use () method, using the plug-in
Import emitter from ". / emitter" Vue.use (emitter)
Step 3: use eventemitter2 in components
Bind event
What is used here is the on method of the official document, passing in eventName and callback, binding events to the instance, and defining callback functions.
Multiple event callbacks can be bound to the same event name. When events are triggered, callback functions with the same name will be executed sequentially.
This.$emit_inst.on (this.$emit_name.CHECK_TYPE_TWO, obj = > {this.value1 = Object.is (NaN,parseInt (obj.value)) obj.type = this.value1? "success": "warning" obj.msg = this.value1? "character": "numeric" console.log ("CHECK_TYPE_TWO first trigger") this.$emit_inst.on (this.$emit_name.CHECK_TYPE_TWO, obj = > {console.log ("CHECK_TYPE_TWO second trigger")})
Trigger event
Event triggers and callbacks are executed synchronously. The execution process is described above.
This.$emit_inst.emit (this.$emit_name.CHECK_TYPE_TWO, obj)
Remove event
When removing an event directly on an instance, it is convenient to use removeAllListeners because only the event name is passed.
BeforeDestroy () {this.$emit_inst.removeAllListeners (this.$emit_name.CHECK_TYPE_TWO)} on "how to use eventemitter2 to achieve Vue component communication" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.