Detailed Explanation of the Use of bus in Vue

  • 2021-11-01 23:34:23
  • OfStack

vue bus mechanism (bus)

In vue, the communication between non-parent and child components can be via vuex or bus bus, which is applicable to different scenarios.

bus is suitable for small projects where data is used by fewer components, but bus is not suitable for medium and large projects where data is used among many components. bus is actually a publish-subscribe mode, which uses the custom event mechanism of vue to publish an event through $emit at the trigger place, and listen to the event through $on on the page that needs to be listened to.

vuex is suitable for medium and large projects, and data is common among multiple components.

Use of component communication bus

Create bus. js under the utils file


// utils - bus.js
import Vue from 'vue'
const bus = new Vue()
export default bus 

1. Pass the value

Send a message


import bus from '@/utils/bus'

The first parameter is the flag variable, and the second parameter is the value of communication


us.$emit('message', 'hello');

Receive information


import bus from '@/utils/bus'

The first parameter is the flag variable, and e in the second parameter is the value of communication


bus.$on('message', (e) => {
 console.log(e)
})

2. Call the method

One component (A) calls the method of another component (B)

Method of B Component


import bus from '@/utils/bus'
mounted () { 
 bus.$on('testA', this.testA) 
},
testA () {
 console.log(' By A Component invocation ')
}

A component call


import bus from '@/utils/bus'
mounted () {
 bus.$emit('testA')
}

Related articles: