Vue bus bus

Problem: Solve the problem of brother component communication, of course you can also choose vuex

First of all three components: main.vue, child1.vue, child2,vue

Note: The registered bus event should be unloaded when the component is destroyed, otherwise it will be mounted multiple times, causing one trigger but multiple responses.

Method 1: Use an empty Vue instance as the central event bus.

main.vue


child1.vue



child2.vue



Method 2: Register in the root component bus

Add the following code to main.js

const bus = new Vue()

Vue.prototype.$bus = bus< /p>

In this way, we don’t need to write bus.js by ourselves, we can directly use it in the build

this.$bus.on(), this.$bus.$emit (), this.$bus.$off()

Method 3: Use the plug-in vue-bus

Install npm install vue-bus --save

Introduced in main.js

import VueBus from'vue-bus';//Central Affairs File bus

Vue.use(VueBus)

In this way, we don’t need to write bus.js to introduce it, we can directly use it in the assembly

this.$bus.on(), this.$bus.$emit(), this.$bus.$off()

main.vue


child1.vue



child2.vue



Leave a Comment

Your email address will not be published.