preface
In the previous article, the lifecycle hook is called by the callHook() method in vUE. For example, the beforeCreate and created lifecycle hooks are called in the initialization chapter as follows:
So what is a Hook Event?
Hook Event
What is?
Hook Event is not mentioned in the official documents of VUE, which is the main reason why many people seldom or almost never use Event Hook, but it does not mean that it cannot be used.
Vue provides life-cycle hooks for developers to perform logical processing at specific time nodes. For example, in mounted life-cycle hooks, prepare data for component rendering.
Hook Event is the function of injecting additional lifecycle methods into components from outside the component by means of custom Event + lifecycle Hook in Vue.
How does it work?
Here is a simple example to quickly understand the use of Hook Events.
Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent () {Vue.com Ponent ()}}} < listview @hook:mounted=”mountedAction”>
@hook: Mounted =”mountedAction” @hook: Mounted =”mountedAction”
This proves that Hook events are designed to inject additional lifecycle methods into components from outside the component via custom Event + lifecycle hooks.
The specific code is as follows:
/ / HTML templates
<div id="app">
<list-view @hook:mounted="mountedAction"></list-view>
</div>
/ / JS logic
<script>
// Third-party VUE components
Vue.component('ListView', {
template:`
- {{ item }}
`.data(){
return {
list: []}},mounted(){
console.log("mounted in ListView...");
setTimeout(() = >{
this.list = [1.2.3.4.5.6];
},1000); }});new Vue({
el: '#app'.methods: {mountedAction(){
console.log("mountedAction from parent..."); }}});</script>
Copy the code
CallHook () method
File Location:src\core\instance\lifecycle.js
The presence of a HookEvent is determined by the vm._hasHookEvent flag in callHook, which is defined in the vue.prototype. $on instance method (see eventsMixin(Vue) for details).
export function callHook (vm: Component, hook: string) {
// #7573 disable dep collection when invoking lifecycle hooks
// Turn on dependency collection before calling
pushTarget()
// Get the corresponding lifecycle hook of type array from the component configuration item
const handlers = vm.$options[hook]
const info = `${hook} hook`
if (handlers) {
for (let i = 0, j = handlers.length; i < j; i++) {
// Call lifecycle functions using apply or call
invokeWithErrorHandling(handlers[i], vm, null, vm, info)
}
}
// If a HookEvent is emitted, call it from $emit, such as hook: Mounted
if (vm._hasHookEvent) {
_events['hook:mounted']
vm.$emit('hook:' + hook)
}
// Close dependency collection when the call is complete
popTarget()
}
Copy the code
InvokeWithErrorHandling () method
File Location:src\core\util\error.js
/* 1. Wrap the logic in the lifecycle hook with a try catch to facilitate exception catching 2. Call lifecycle hooks: call through apply with args, otherwise call through call 3. Returns the call result */
export function invokeWithErrorHandling (
handler: Function,
context: any,
args: null | any[],
vm: any,
info: string
) {
let res
try {
res = args ? handler.apply(context, args) : handler.call(context)
if(res && ! res._isVue && isPromise(res) && ! res._handled) { res.catch(e= > handleError(e, vm, info + ` (Promise/async)`))
// issue #9511
// Avoid multiple catches in nested calls
res._handled = true}}catch (e) {
// Exception handling
handleError(e, vm, info)
}
return res
}
Copy the code
conclusion
What is the principle of Hook Events?
First, Hook events are used to inject additional lifecycle methods into components from outside the component, mainly through custom events + lifecycle hooks.
vue
In processing components such as<comp @hook:lifecycle="customMethod" />
, will pass the eventVm. $on () the Vue. Prototype $on ()
Method, and encountered in the formathook:xx
The event will bevm._hasHookEvent
Set totrue
, indicates that the component hasHook Event
- Through the
callHook()
When a method calls a lifecycle hook, it executes the corresponding lifecycle hook on the component in a circular fashion - After executing a lifecycle hook on a post-component, passes
vm._hasHookEvent
Identifies whether the current component existsHook Event
If it exists, passVm $emit (' hook: XXX) namely Vue. Prototype $emit ()
The method callvm._events['hook:xxx']
All handlers on the event
The articles
- What does vUE initialization do?
- How to understand vUE responsiveness?
- How does vUE update asynchronously?
- Do you really understand the Vue global Api?
- Did you lose the instance method in VUE?