一文帶你理解 Vue 中的生命周期
前言:
每個 Vue
實(shí)例在被創(chuàng)建之前都要經(jīng)過一系列的初始化過程。例如需要設(shè)置數(shù)據(jù)監(jiān)聽、編譯模板、掛載實(shí)例到 DOM、在數(shù)據(jù)變化時更新 DOM
等。同時在這個過程中也會運(yùn)行一些叫做生命周期鉤子的函數(shù),給予用戶機(jī)會在一些特定的場景下添加他們自己的代碼。
源碼中最終執(zhí)行生命周期的函數(shù)都是調(diào)用 callHook
方法,它的定義在 src/core/instance/lifecycle
中:
export function callHook (vm: Component, hook: string) { // #7573 disable dep collection when invoking lifecycle hooks pushTarget() const handlers = vm.$options[hook] if (handlers) { for (let i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm) } catch (e) { handleError(e, vm, `${hook} hook`) } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook) } popTarget() }
callHook
函數(shù)的邏輯很簡單,根據(jù)傳入的字符串 hook,去拿到 vm.$options[hook]
對應(yīng)的回調(diào)函數(shù)數(shù)組,然后遍歷執(zhí)行,執(zhí)行的時候把 vm 作為函數(shù)執(zhí)行的上下文。
1、beforeCreate & created
beforeCreate
和 created
函數(shù)都是在實(shí)例化 Vue 的階段,在 _init 方法中執(zhí)行的,它的定義在 src/core/instance/init.js
中:
Vue.prototype._init = function (options?: Object) { // ... initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate') initInjections(vm) // resolve injections before data/props initState(vm) initProvide(vm) // resolve provide after data/props callHook(vm, 'created') // ... }
可以看到 beforeCreate
和 created
的鉤子調(diào)用是在 initState
的前后,initState
的作用是初始化 props
、data
、methods
、watch
、computed
等屬性,之后我們會詳細(xì)分析。那么顯然 beforeCreate
的鉤子函數(shù)中就不能獲取到 props
、data
中定義的值,也不能調(diào)用 methods
中定義的函數(shù)。
在這倆個鉤子函數(shù)執(zhí)行的時候,并沒有渲染 DOM,所以我們也不能夠訪問 DOM,一般來說,如果組件在加載的時候需要和后端有交互,放在這倆個鉤子函數(shù)執(zhí)行都可以,如果是需要訪問 props
、data
等數(shù)據(jù)的話,就需要使用 created
鉤子函數(shù)。之后我們會介紹 vue-router
和 vuex 的時候會發(fā)現(xiàn)它們都混合了 beforeCreatd
鉤子函數(shù)。
2、beforeMount & mounted
顧名思義,beforeMount
鉤子函數(shù)發(fā)生在 mount
,也就是 DOM 掛載之前,它的調(diào)用時機(jī)是在 mountComponent
函數(shù)中,定義在 src/core/instance/lifecycle.js
中:
export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean ): Component { vm.$el = el // ... callHook(vm, 'beforeMount') let updateComponent /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { updateComponent = () => { const name = vm._name const id = vm._uid const startTag = `vue-perf-start:${id}` const endTag = `vue-perf-end:${id}` mark(startTag) const vnode = vm._render() mark(endTag) measure(`vue ${name} render`, startTag, endTag) mark(startTag) vm._update(vnode, hydrating) mark(endTag) measure(`vue ${name} patch`, startTag, endTag) } } else { updateComponent = () => { vm._update(vm._render(), hydrating) } } // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate') } } }, true /* isRenderWatcher */) hydrating = false // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true callHook(vm, 'mounted') } return vm }
在執(zhí)行 vm. render()
函數(shù)渲染 VNode 之前,執(zhí)行了 beforeMount
鉤子函數(shù),在執(zhí)行完 vm. update()
把 VNode patch
到真實(shí) DOM 后,執(zhí)行 mouted
鉤子。注意,這里對 mouted
鉤子函數(shù)執(zhí)行有一個判斷邏輯,vm.$vnode
如果為 null,則表明這不是一次組件的初始化過程,而是我們通過外部 new Vue
初始化過程。那么對于組件,它的 mounted
時機(jī)在哪兒呢?
組件的 VNode patch
到 DOM 后,會執(zhí)行 invokeInsertHook
函數(shù),把 insertedVnodeQueue
里保存的鉤子函數(shù)依次執(zhí)行一遍,它的定義在 src/core/vdom/patch.js
中:
function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue } else { for (let i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]) } } }
該函數(shù)會執(zhí)行 insert
這個鉤子函數(shù),對于組件而言,insert 鉤子函數(shù)的定義在 src/core/vdom/create-component.js
中的 componentVNodeHooks
中:
const componentVNodeHooks = { // ... insert (vnode: MountedComponentVNode) { const { context, componentInstance } = vnode if (!componentInstance._isMounted) { componentInstance._isMounted = true callHook(componentInstance, 'mounted') } // ... }, }
我們可以看到,每個子組件都是在這個鉤子函數(shù)中執(zhí)行 mouted
鉤子函數(shù),并且我們之前分析過,insertedVnodeQueue
的添加順序是先子后父,所以對于同步渲染的子組件而言,mounted
鉤子函數(shù)的執(zhí)行順序也是先子后父。
3、beforeUpdate & updated
顧名思義,beforeUpdate
和 updated
的鉤子函數(shù)執(zhí)行時機(jī)都應(yīng)該是在數(shù)據(jù)更新的時候,到目前為止,我們還沒有分析 Vue
的數(shù)據(jù)雙向綁定、更新相關(guān),下一章我會詳細(xì)介紹這個過程。
beforeUpdate
的執(zhí)行時機(jī)是在渲染 Watcher
的 before
函數(shù)中
export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean ): Component { // ... // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate') } } }, true /* isRenderWatcher */) // ... }
注意這里有個判斷,也就是在組件已經(jīng) mounted
之后,才會去調(diào)用這個鉤子函數(shù)。
update
的執(zhí)行時機(jī)是在flushSchedulerQueue
函數(shù)調(diào)用的時候, 它的定義在 src/core/observer/scheduler.js
中:
function flushSchedulerQueue () { // ... // 獲取到 updatedQueue callUpdatedHooks(updatedQueue) } function callUpdatedHooks (queue) { let i = queue.length while (i--) { const watcher = queue[i] const vm = watcher.vm if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated') } } }
flushSchedulerQueue
函數(shù)我們之后會詳細(xì)介紹,可以先大概了解一下,updatedQueue
是 更新了的 wathcer
數(shù)組,那么在 callUpdatedHooks
函數(shù)中,它對這些數(shù)組做遍歷,只有滿足當(dāng)前 watcher
為 vm._watcher
以及組件已經(jīng) mounted
這兩個條件,才會執(zhí)行 updated
鉤子函數(shù)。
我們之前提過,在組件 mount
的過程中,會實(shí)例化一個渲染的 Watcher
去監(jiān)聽 vm 上的數(shù)據(jù)變化重新渲染,這斷邏輯發(fā)生在 mountComponent
函數(shù)執(zhí)行的時候:
export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean ): Component { // ... // 這里是簡寫 let updateComponent = () => { vm._update(vm._render(), hydrating) } new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate') } } }, true /* isRenderWatcher */) // ... }
那么在實(shí)例化 Watcher
的過程中,在它的構(gòu)造函數(shù)里會判斷 isRenderWatcher
,接著把當(dāng)前 watcher
的實(shí)例賦值給 vm._watcher
,定義在 src/core/observer/watcher.js
中:
export default class Watcher { // ... constructor ( vm: Component, expOrFn: string | Function, cb: Function, options?: ?Object, isRenderWatcher?: boolean ) { this.vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // ... } }
同時,還把當(dāng)前 wathcer
實(shí)例 push 到 vm. watchers
中,vm. watcher
是專門用來監(jiān)聽 vm 上數(shù)據(jù)變化然后重新渲染的,所以它是一個渲染相關(guān)的 watcher
,因此在 callUpdatedHooks
函數(shù)中,只有 vm._watcher
的回調(diào)執(zhí)行完畢后,才會執(zhí)行 updated
鉤子函數(shù)。
4、beforeDestroy & destroyed
顧名思義,beforeDestroy
和 destroyed
鉤子函數(shù)的執(zhí)行時機(jī)在組件銷毀的階段,組件的銷毀過程之后會詳細(xì)介紹,最終會調(diào)用 $destroy
方法,它的定義在 src/core/instance/lifecycle.js
中:
Vue.prototype.$destroy = function () { const vm: Component = this if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy') vm._isBeingDestroyed = true // remove self from parent const parent = vm.$parent if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm) } // teardown watchers if (vm._watcher) { vm._watcher.teardown() } let i = vm._watchers.length while (i--) { vm._watchers[i].teardown() } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount-- } // call the last hook... vm._isDestroyed = true // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null) // fire destroyed hook callHook(vm, 'destroyed') // turn off all instance listeners. vm.$off() // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null } }
beforeDestroy
鉤子函數(shù)的執(zhí)行時機(jī)是在 destroy
函數(shù)執(zhí)行最開始的地方,接著執(zhí)行了一系列的銷毀動作,包括從parent
的children
中刪掉自身,刪除 watcher
,當(dāng)前渲染的 VNode
執(zhí)行銷毀鉤子函數(shù)等,執(zhí)行完畢后再調(diào)用 destroy
鉤子函數(shù)。
在 $destroy 的執(zhí)行過程中,它又會執(zhí)行 vm. patch (vm._vnode, null)
觸發(fā)它子組件的銷毀鉤子函數(shù),這樣一層層的遞歸調(diào)用,所以 destroy
鉤子函數(shù)執(zhí)行順序是先子后父,和 mounted 過程一樣。
5、activated & deactivated
activated 和 deactivated
鉤子函數(shù)是專門為 keep-alive
組件定制的鉤子,我們會在介紹 keep-alive
組件的時候詳細(xì)介紹,這里先留個懸念。
總結(jié):
這一節(jié)主要介紹了 Vue 生命周期中各個鉤子函數(shù)的執(zhí)行時機(jī)以及順序,通過分析,我們知道了如在 created
鉤子函數(shù)中可以訪問到數(shù)據(jù),在 mounted
鉤子函數(shù)中可以訪問到 DOM,在 destroy
鉤子函數(shù)中可以做一些定時器銷毀工作,了解它們有利于我們在合適的生命周期去做不同的事情。
到此這篇關(guān)于一文帶你理解 Vue 中的生命周期的文章就介紹到這了,更多相關(guān) Vue 中的生命周期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解使用vue腳手架工具搭建vue-webpack項(xiàng)目
本篇文章主要介紹了詳解使用vue腳手架工具搭建vue-webpack項(xiàng)目,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-05-05淺談ElementUI中switch回調(diào)函數(shù)change的參數(shù)問題
今天小編就為大家分享一篇淺談ElementUI中switch回調(diào)函數(shù)change的參數(shù)問題,具有很好的價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08Vuex進(jìn)行Echarts數(shù)據(jù)頁面初始化后如何更新dom
這篇文章主要為大家詳細(xì)介紹了使用Vuex做Echarts數(shù)據(jù)時,當(dāng)頁面初始化后如何更新dom,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11vue循環(huán)中點(diǎn)擊選中再點(diǎn)擊取消(單選)的實(shí)現(xiàn)
這篇文章主要介紹了vue循環(huán)中點(diǎn)擊選中再點(diǎn)擊取消(單選)的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09