1, a method
And use $ on $ emit
// Parent.vue
<Child @mounted="doSomething"/>
// Child.vue
mounted() {
this.$emit("mounted");
}
2, using the hook
// Parent.vue
<Child @hook:mounted="doSomething" ></Child>
doSomething() {
the console.log ( 'parent monitor assembly mounted to the hook function ...' );
},
// Child.vue
mounted(){
the console.log ( 'triggered subassembly mounted hooking function ...' );
},
// output above order:
// sub-assembly mounted trigger hook function ...
// parent component to monitor mounted hook function ...
hook principle is: vue lifecycle hook function
(1) vue Source
vm._self = vm
initLifecycle (vm) // initialize lifecycle
initEvents (vm) // Initialize event
initRender (vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
(2) callHook source
export function callHook (vm: Component, hook: string) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget()
handlers const . = $ VM Options [Hook] // of the options, the life cycle of the function
const info = `$ {} hook` Hook
IF (handlers) {
for (the let I = 0, J = handlers.length; I <J; ++ I ) {
invokeWithErrorHandling(handlers[i], vm, null, vm, info)
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook)
}
popTarget()
}
Note: . $ EMIT VM ( 'Hook:' Hook +), i.e., the hooking function may be triggered. the Prerequisite is_hasHookEvent为true。
(3)_hasHookEvent源码
const hookRE = /^hook:/ // 以hook:开头
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {
const vm: Component = this
if (Array.isArray(event)) {
for (let i = 0, l = event.length; i < l; i++) {
vm.$on(event[i], fn)
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn)
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true
}
}
return vm
}
即:
当使用了$on
方法监听事件时,如果事件名以 hooks:
作为前缀,那么这个事件会被当做hookEvent
,注册事件回调的同时,vm._hasHookEvent
会被置为true
,当使用callHook
调用生命周期函数时,由于_hasHookEvent
为true
,所以会$emit('hooks:xxx')
,注册的生命周期函数就会执行。
最后的最后:
添加钩子的方法有:
- 在
Vue
组件选项中添加; - 在模板中通过
@hooks:created
这种形式; vm.$on('hooks:created', cb)
或者vm.$once('hooks:created', cb)
。