$on
The method is an instance method of the Vue object, which is mainly used to listen to a custom event in the Vue instance. When a custom event is triggered, a callback function can be executed to respond to the event.
The syntax of the $on method is as follows:
vm.$on(event,callback)
for example:
const vm = new Vue()
vm.$on('openBox', data =>{
console.log('开宝箱~', data)
})
The above case is to listen to the openBox event of the instantiated object vm, and use an anonymous function as a callback function to execute the anonymous function (callback function) when the test event is triggered.
So how to trigger the event?
该实例化对象的$emit
Triggered by an event, the syntax is as follows:
vm.$emit(event, 会调函数传参)
for example:
const vm = new Vue()
vm.$on('openBox', data =>{
console.log('开宝箱~', data)
})
callback(){
vm.$emit('openBox', {
name:"超超"})
}
In the above case, when the callback function is executed, the openBox method of the instantiated object vm will be triggered, and at the same time, the callback function bound to $on will be executed, and the printed value will be "open treasure box~, {name: 'super super' }"
tips: The $on method only listens to custom events on the current Vue instance, without affecting other instances