Event bus in Vue

If you need to communicate in cross-level or sibling components, using the $emit method multiple times will be cumbersome and inflexible

The event bus can emit and monitor events, just like a vue instance

Add $bus to the vue prototype in main.js

Vue.prototype.$bus = new Vue()

In a certain component A, use $emit to emit events, generally used for data updates

this.$bus.$emit("事件名")

In another component B, use $on to monitor the event, the data in A changes, B can be monitored, and then perform subsequent operations

this.$bus.$on("事件名",function(){
    
     相关操作 })

Note: $bus.on should be used in created(). If it is used in mounted, it may not receive events from other components from created().

Guess you like

Origin blog.csdn.net/michaelxuzhi___/article/details/106063723