首頁  >  文章  >  web前端  >  Vue的生命週期及原始碼實作(程式碼)

Vue的生命週期及原始碼實作(程式碼)

不言
不言原創
2018-09-07 16:57:482192瀏覽

這篇文章帶給大家的內容是關於Vue的生命週期及原始碼實現(程式碼) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

透過學習,我們已經學會了Vue的所有基本語法,包括:

1、{{Mustache}} 語法  
 2、v-if、v-else、v-else-if、v-show  
 3、v-for
 4、v-bind
 5、v-model
6.v-on

如果大家已經對這些語法牢記於心了,那麼請繼續往下看,如果大家對這些語法掌握的並不是很熟練的話,那麼希望大家再去回顧一下前面的內容。

這一章我們學習Vue的生命週期,我們先來看看Vue的生命週期的定義。

每個 Vue 實例在被創建時都要經過一系列的初始化過程——例如,需要設定資料監聽、編譯模板、將實例掛載到 DOM 並在資料變更時更新 DOM 等。同時在這個過程中也會執行一些叫做生命週期鉤子的函數,這給了使用者在不同階段加入自己的程式碼的機會。

這是Vue官網上提供的描述訊息,簡單來說就是:在Vue從創建實例到最終完全消亡的過程中,會執行一系列的方法,用於對應當前Vue的狀態,這些方法我們叫它:生命週期鉤子。我們來看看下面的生命週期圖示:

Vue的生命週期及原始碼實作(程式碼)

在上面的圖示中,共展示出來8個生命週期鉤子函數,這8個函數就描繪出來了Vue整個的運行週期。而截止到目前的Vue版本-2.5.16。 Vue的宣告週期鉤子總共為11個,除去剛才的8個之外,還有3個關於元件的生命週期鉤子。我們來看看所有的鉤子函數解釋,配合上面的圖示,可以更好地理解Vue的運行週期

1、beforeCreate:在實例初始化之後,資料觀測 (data observer) 和 event/watcher 事件配置之前被呼叫。
 2、created:在實例建立完成後立即被呼叫。在這一步,實例已完成以下的配置:資料觀測 (data observer),屬性和方法的運算,watch/event 事件回呼。然而,掛載階段還沒開始,$el 屬性目前不可見。
 3、beforeMount:在掛載開始之前被呼叫:相關的 render 函數首次被呼叫。
 4、mounted:el 被新建立的 vm.$el 替換,並掛載到實例上去之後呼叫該鉤子。如果root 實例掛載了一個文檔內元素,當mounted 被呼叫時vm.$el 也在文檔內(PS:注意mounted 不會承諾所有的子元件也都一起被掛載。如果你希望等到整個視圖都渲染完畢,可以用vm.$nextTick 替換掉mounted:)。 vm.$nextTick會在後面的章節詳細講解,這裡大家需要知道有這個東西。
 5、beforeUpdate:資料更新時調用,發生在虛擬 DOM 打補丁之前。這裡適合在更新之前存取現有的 DOM,例如手動移除已新增的事件監聽器。
 6、updated:由於資料變更導致的虛擬 DOM 重新渲染和打補丁,在這之後會呼叫該鉤子。當這個鉤子被呼叫時,元件 DOM 已經更新,所以你現在可以執行依賴 DOM 的操作。然而在大多數情況下,你應該避免在此期間更改狀態。如果要相應狀態改變,通常最好使用計算屬性或 watcher 取代(PS:計算屬性與watcher會在後面的章節進行介紹)。
 7、activated:keep-alive 元件啟動時調用(PS:與元件相關,關於keep-alive會在講解元件的時候為大家介紹)。
 8、deactivated:keep-alive 元件停用時呼叫(PS:與元件相關,關於keep-alive會在講解元件的時候為大家介紹)。
 9、beforeDestroy:實例銷毀之前呼叫。在這一步,實例仍然完全可用。
 10、destroyed:Vue 實例銷毀後呼叫。呼叫後,Vue 實例所指示的所有東西都會解綁定,所有的事件監聽器會被移除,所有的子實例也會被銷毀。
 11、errorCaptured(2.5.0 新增):當捕獲一個來自子孫元件的錯誤時被呼叫。此鉤子會收到三個參數:錯誤物件、發生錯誤的元件實例以及一個包含錯誤來源資訊的字串。此鉤子可以傳回 false 以防止該錯誤繼續向上傳播。

這就是Vue(2.5.16)中所有的生命週期鉤子,為了更方便大家的理解,我們來看一下,在Vue的程式碼中,從創建銷毀是如何在實現的。大家可以點這裡下載Vue的最新程式碼。

我們先大致來看Vue原始碼的基礎架構

.
├── BACKERS.md ├── LICENSE
├── README.md├── benchmarks
├── dist
├── examples
├── flow
├── node_modules
├── package.json├── packages
├── scripts
├── src
├── test
├── types
└── yarn.lock

這是下載下來程式碼之後的一級目錄,dist資料夾下為Vue編譯之後的程式碼,我們平常引入的Vue.js檔案都在這裡 Vue使用了flow作為JavaScript靜態類型檢查工具,相關的程式碼都在flow資料夾下面scripts資料夾下面是程式碼建置的相關配置,Vue主要使用Rollup進行的程式碼建置src資料夾下面就是所有Vue的原始碼。我們這裡不對其他的內容進行過多的描述,還是專注於我們的主題,Vue的宣告週期程式碼是如何實作,我們看一下src資料夾。

.
├── compiler :Vue编译相关
├── core    :Vue的核心代码
├── platforms   :web/weex平台支持,入口文件
├── server  :服务端
├── sfc :解析.vue文件
└── shared  :公共代码

這是我們src資料夾下的目錄結構,而我們Vue產生的地方就在/src/core/instance/index. js中。

function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }  this._init(options)
}

我們可以看到:Vue是一個方法,是使用Function來實現的建構函數,所以我們只能透過 new 的方式來去建立Vue的實例。 接著透過Vue實例_init方法來進行Vue的初始化。 _init是Vue透過prototype來實現的一個原型屬性。我們來看看他的_init方法實作。

/src/core/instance/init.js資料夾下,Vue實作了_init方法

Vue.prototype._init = function (options?: Object) {    ...
    // expose real self
    vm._self = vm
    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')    ...
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
 }

我主要看與它生命週期有關的程式碼,我們可以看到,Vue先呼叫了initLifecycle(vm)、initEvents(vm)、initRender(vm)這三個方法,用於初始化生命週期、事件、渲染函數,這些過程發生在Vue初始化的過程(_init方法)中,並在呼叫beforeCreate鉤子之前。

然後Vue透過callHook (vm: Component, hook: string)方法來去呼叫鉤子函數(hook),它接收vm(Vue實例物件),hook(鉤子函數名稱)來去執行生命週期函數。在Vue中幾乎所有的鉤子(errorCaptured除外)函數執行都是透過callHook (vm: Component, hook: string)來呼叫的。讓我們來看看callHook的程式碼,在/src/core/instance/lifecycle.js下:

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(&#39;hook:&#39; + hook)
  }
  popTarget()
}

它的邏輯也非常簡單,根據傳入的hook從實例中拿到對應的回呼函數陣列(在/packages/vue-template-compiler/browser.js下的LIFECYCLE_HOOKS),然後便利執行。

然後在初始化生命週期、事件、渲染函數之後呼叫了beforeCreate鉤子,在這個時候:我們還沒辦法取得到 data、props等資料

在呼叫了beforeCreate鉤子之後,Vue呼叫了initInjections(vm)、initState(vm)、initProvide(vm)這三個方法用來初始化data、props、watcher等等,在這些初始化執行完成之後,呼叫了created鉤子函數,在這個時候:我們已經可以取得到data、props 等資料了,但是Vue並沒有開始渲染DOM,所以我們還不能夠訪問DOM(PS:我們可以透過vm.$nextTick來訪問,在後面的章節我們會詳細講解)。

在呼叫了created鉤子之後,Vue開始進行DOM的掛載,執行vm.$mount(vm.$options. el),在Vue中DOM的掛載就是透過Vue.prototype.$mount這個原型方法來去實現的。 Vue.prototype.$mount原型方法的宣告是在/src/platforms/web/entry-runtime-with-compiler.js,我們來看看這個程式碼的實作:

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)  
  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== &#39;production&#39; && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )    return this
  }  const options = this.$options  
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template    
    if (template) {      
    if (typeof template === &#39;string&#39;) {        
    if (template.charAt(0) === &#39;#&#39;) {
          template = idToTemplate(template)          
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== &#39;production&#39; && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {        if (process.env.NODE_ENV !== &#39;production&#39;) {
          warn(&#39;invalid template option:&#39; + template, this)
        }        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }    if (template) {      
    /* istanbul ignore if */
      if (process.env.NODE_ENV !== &#39;production&#39; && config.performance && mark) {
        mark(&#39;compile&#39;)
      }      
      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns      
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== &#39;production&#39; && config.performance && mark) {
        mark(&#39;compile end&#39;)
        measure(`vue ${this._name} compile`, &#39;compile&#39;, &#39;compile end&#39;)
      }
    }
  }  return mount.call(this, el, hydrating)
}
/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */function getOuterHTML (el: Element): string {
  if (el.outerHTML) {    
  return el.outerHTML
  } else {    
  const container = document.createElement(&#39;p&#39;)
    container.appendChild(el.cloneNode(true))    
    return container.innerHTML
  }
}

這部分程式碼的主要作用:就是進行template模板的解析#。從上面的程式碼可以看出,el不允許被掛載到bodyhtml這樣的根標籤上面。 接著判斷是否有render函數-> if (!options.render) {...},然後判斷有沒有template,template可以是string類型的idDOM節點。沒有的話則解析el作為template。由上面的程式碼可以看出我們無論是使用單一檔案元件(.Vue)或透過el、template屬性,它最終都會通過render函數的形式來進行整個模板的解析

由我們的圖示可以看出模板解析完成之後,會呼叫beforeMount鉤子,那麼這個beforeMount鉤子是在哪裡被呼叫的呢?我們接著往下看。 $mount原型方法有一個可重複使用的設計,在/src/platforms/web/runtime/index.js下,有這麼一段程式碼

// public mount method
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

这是一个公共的挂载方法,目的是为了被runtime only版本的Vue直接使用,它调用了mountComponent方法。我们看一下mountComponent方法的实现,实现在/src/core/instance/lifecycle.js下。

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el  
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode    
    if (process.env.NODE_ENV !== &#39;production&#39;) {      
    /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== &#39;#&#39;) ||
        vm.$options.el || el) {
        warn(          
        &#39;You are using the runtime-only build of Vue where the template &#39; +          
        &#39;compiler is not available. Either pre-compile the templates into &#39; +          
        &#39;render functions, or use the compiler-included build.&#39;,
          vm
        )
      } else {
        warn(          
        &#39;Failed to mount component: template or render function not defined.&#39;,
          vm
        )
      }
    }
  }
  callHook(vm, &#39;beforeMount&#39;)

  let updateComponent  
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== &#39;production&#39; && 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&#39;s constructor
  // since the watcher&#39;s initial patch may call $forceUpdate (e.g. inside child
  // component&#39;s mounted hook), which relies on vm._watcher being already defined
  new Watcher(vm, updateComponent, noop, null, 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, &#39;mounted&#39;)
  }  
  return vm
}

由上面的代码可以看出在执行vm._render()之前,调用了callHook(vm, 'beforeMount'),这个时候相关的 render 函数首次被调用,调用完成之后,执行了callHook(vm, 'mounted')方法,标记着el 被新创建的 vm.$el 替换,并被挂载到实例上。

然后就进入了我们页面正常交互的时间,也就是beforeUpdateupdated这两个回调钩子的执行时机。这两个钩子函数是在数据更新的时候进行回调的函数,Vue在/src/core/instance/lifecycle.js文件下有一个_update的原型声明:

Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
    const vm: Component = this    
    if (vm._isMounted) {
      callHook(vm, &#39;beforeUpdate&#39;)
    }    const prevEl = vm.$el
    const prevVnode = vm._vnode    
    const prevActiveInstance = activeInstance
    activeInstance = vm
    vm._vnode = vnode    
    // Vue.prototype.__patch__ is injected in entry points
    // based on the rendering backend used.
    if (!prevVnode) {      
    // initial render
      vm.$el = vm.__patch__(
        vm.$el, vnode, hydrating, false 
        /* removeOnly */,
        vm.$options._parentElm,
        vm.$options._refElm
      )      
      // no need for the ref nodes after initial patch
      // this prevents keeping a detached DOM tree in memory (#5851)
      vm.$options._parentElm = vm.$options._refElm = null
    } else {      
    // updates
      vm.$el = vm.__patch__(prevVnode, vnode)
    }
    activeInstance = prevActiveInstance    
    // update __vue__ reference
    if (prevEl) {
      prevEl.__vue__ = null
    }    if (vm.$el) {
      vm.$el.__vue__ = vm
    }    
    // if parent is an HOC, update its $el as well
    if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
      vm.$parent.$el = vm.$el
    }    
    // updated hook is called by the scheduler to ensure that children are
    // updated in a parent&#39;s updated hook.
  }

我们可以看到在如果_isMountedture的话(DOM已经被挂载)则会调用callHook(vm, 'beforeUpdate')方法,然后会对虚拟DOM进行重新渲染。然后在/src/core/observer/scheduler.js下的flushSchedulerQueue()函数中渲染DOM,在渲染完成调用callHook(vm, 'updated'),代码如下:。

/**
 * Flush both queues and run the watchers.
 */function flushSchedulerQueue () { ...
  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, &#39;updated&#39;)
    }
  }
}

当Vue实例需要进行销毁的时候回调beforeDestroy 、destroyed这两个函数钩子,它们的实现是在/src/core/instance/lifecycle.js下的Vue.prototype.$destroy中:

  Vue.prototype.$destroy = function () {
    const vm: Component = this    
    if (vm._isBeingDestroyed) {      
    return
    }
    callHook(vm, &#39;beforeDestroy&#39;)
    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, &#39;destroyed&#39;)    
    // 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
    }
  }

$destroy这个原型函数中,执行了Vue的销毁操作,我们可以看到在执行销毁操作之前调用了callHook(vm, 'beforeDestroy'),然后执行了一系列的销毁操作,包括删除掉所有的自身(self)、_watcher、数据引用等等,删除完成之后调用callHook(vm, 'destroyed')

截止到这里,整个Vue生命周期图示中的所有生命周期钩子都已经被执行完成了。那么剩下的activated、deactivated、errorCaptured这三个钩子函数是在何时被执行的呢?我们知道这三个函数都是针对于组件(component)的钩子函数。其中activated、deactivated这两个钩子函数分别是在keep-alive 组件激活和停用之后回调的,它们不牵扯到整个Vue的生命周期之中activated、deactivated这两个钩子函数的实现代码都在/src/core/instance/lifecycle.js下:

export function activateChildComponent (vm: Component, direct?: boolean) {
  if (direct) {
    vm._directInactive = false
    if (isInInactiveTree(vm)) {      
    return
    }
  } else if (vm._directInactive) {    
  return
  }  if (vm._inactive || vm._inactive === null) {
    vm._inactive = false
    for (let i = 0; i < vm.$children.length; i++) {
      activateChildComponent(vm.$children[i])
    }
    callHook(vm, &#39;activated&#39;)
  }
}

export function deactivateChildComponent (vm: Component, direct?: boolean) {
  if (direct) {
    vm._directInactive = true
    if (isInInactiveTree(vm)) {      return
    }
  }  if (!vm._inactive) {
    vm._inactive = true
    for (let i = 0; i < vm.$children.length; i++) {
      deactivateChildComponent(vm.$children[i])
    }
    callHook(vm, &#39;deactivated&#39;)
  }
}

而对于errorCaptured来说,它是在2.5.0之后新增的一个钩子函数,它的代码在/src/core/util/error.js中:

export function handleError (err: Error, vm: any, info: string) {
  if (vm) {    let cur = vm    while ((cur = cur.$parent)) {      
  const hooks = cur.$options.errorCaptured      
  if (hooks) {        
  for (let i = 0; i < hooks.length; i++) {          
  try {            
  const capture = hooks[i].call(cur, err, vm, info) === false
            if (capture) return
          } catch (e) {
            globalHandleError(e, cur, &#39;errorCaptured hook&#39;)
          }
        }
      }
      
    }
  }
  globalHandleError(err, vm, info)
}function globalHandleError (err, vm, info) {
  if (config.errorHandler) {    
  try {      
  return config.errorHandler.call(null, err, vm, info)
    } catch (e) {
      logError(e, null, &#39;config.errorHandler&#39;)
    }
  }
  logError(err, vm, info)
}function logError (err, vm, info) {
  if (process.env.NODE_ENV !== &#39;production&#39;) {
    warn(`Error in ${info}: "${err.toString()}"`, vm)
  }  /* istanbul ignore else */
  if ((inBrowser || inWeex) && typeof console !== &#39;undefined&#39;) {
    console.error(err)
  } else {    
  throw err
  }
}

他是唯一一个没有通过callHook方法来执行的钩子函数,而是直接通过遍历cur(vm).$options.errorCaptured,来执行config.errorHandler.call(null, err, vm, info)的钩子函数。整个逻辑的结构与callHook使非常类似的。

截止到目前Vue中所有的生命周期钩子我们都已经介绍完成了,其中涉及到了一些源码的基础,是因为我觉得配合源码来一起看的话,会对整个Vue的运行过程有个更好的理解。大家一定要下载下来Vue的源代码,对照着我们的讲解来走一遍这个流程。

相关推荐:

vue生命周期、vue实例、模板语法

图概PHP生命周期,PHP生命周期

以上是Vue的生命週期及原始碼實作(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn