Home > Article > Web Front-end > Is the vue event bus abolished?
vue3 canceled the global event bus because of low security. The global event bus is a global any-component communication technology, that is, communication between any components can be achieved. In vue3, if you want to use the global event bus, you need to introduce the third-party library mitt or tiny-emitter.
The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.
vue3 canceled the global event bus due to low security.
The global event bus is a global any component communication technology.
As the name suggests, communication between any components can be achieved.
Its communication is achieved through a puppet, a puppet that can be accessed by all components. It is named $bus
We can use the life cycle hook directly in the entry file mian.jsbeforecreated
Create directly $bus
beforeCreate() { Vue.prototype.$bus = this }
Remember to write the hook before
mounting.
When used:
Use mounted
hook binding event monitoring in the component that needs to receive data
mounted() { this.$bus.$on('hello',(data) => { console.log(data); }) },
This method can be triggered in the operation that needs to be sent in the component that needs to send data
methods: { sendStudentName(){ this.$bus.$emit('hello',this.name) } },
It’s not over yet, if When the component is destroyed, remember to unbind the event and unbind it wherever it was bound. Use beforeDestroy
hook
beforeDestroy() { this.$bus.$off('hello') },
In vue3, the global event bus is cancelled. If we want to use it, we need to introduce a third-party library mitt
or tiny- emitter
1. Install the mitt library
npm i mitt -s
2. Encapsulate a js file in the root directory so that it can be imported into the component.
It is best to name the file by name. For example, eventBus.js
Content:
//导入 import mitt from 'mitt'; //定义,定义也最好见名知义 const emitter = mitt(); //暴露 export default emitter;
3. Use
1) Components that communicate with each other need to import js
import emitter from '../../eventBus'
2) The component that receives the data is bound to the event listener in setup()
setup(){ emitter.on('event',(info) => { ... }) return{} }
The arrow function here can also be replaced by a normal function
3) Send Data can be transferred when the data component is triggered.
setup(){ function send(info) { emitter.emit('event',info) ) return{} }
4) Before the component is destroyed, unbind the event.
onBeforeUnmount(()=>{ emitter.off("event", onEvent); })
If you use a normal function, put the function in the second parameter, If it is an arrow function, there is no need to write it. As above onEvent
[Related recommendations: vuejs video tutorial, web front-end development]
The above is the detailed content of Is the vue event bus abolished?. For more information, please follow other related articles on the PHP Chinese website!