Simple explanation of bus bus of vue
- 2021-11-14 04:59:57
- OfStack
Simple use of bus bus in vue
Scene description:
A component includes B and C components, while B component includes D component. What if D component wants to trigger the method of C component in A component?
Of course, there is a scheme, which uses state management
vuex
Yes, use
$emit
Transmission is OK, but I want to try to use bus bus.
As follows:
emit of bus is triggered in D component, and then on of bus bus is used to trigger method in A component;
In the D component
dataLoad(){
console.log(' Finish loading trigger event ');
this.$bus.$emit('itemDataLoad')
// this.$bus.$emit(' Event name ', Parameter ) // No. 1 2 Can be a parameter
},
In the A component
mounted() {
// Eavesdropping item The data in is loaded
this.$bus.$on('itemDataLoad', () => {
console.log(' Finish loading data ');
})
// this.$bus.$on(' Event name ', Callback function ( Parameter ))
},
Of course, in the A component, through
this.$refs
You can trigger events in the C component, and so on
Another step is
$bus
The default does not exist. Try printing
this.$bus为undefined
Ah;
Don't worry, add $bus to main. js;
// bus Bus vue Instances
Vue.prototype.$bus = new Vue()
Of course, the bus bus can be removed in the life cycle;
this.$bus.$off();
Anti-shake function of record encapsulation
// Anti-shake function
debounce: function (fun, delay) {
let timer = null
// Receives the value of the parameter passed in when the function is called ...args Can be multiple
return function (...args) {
if (tiemr) return
timer = setTimeout(() => {
fun.apply(this, args)
}, delay);
}
}
const refresh = debounce(xxx, 500)
refresh(' Parameter 1', ' Parameter 2', ' Parameter 3')