vue實例化過程

  咱們在用vue進行開發項目時,是否存在疑惑,new Vue(xxx)的過程當中,究竟發生了什麼?定義的數據,是如何綁定到視圖上的?本篇主要介紹在實例化vue時,主要作了哪些事,文章比較長,主要篇幅內容爲數據初始化和數據視圖綁定過程。主要代碼執行時序圖以下所示:html

  

   在vue源碼中,vue構造函數的定義是在/src/core/instance下,入口文件index.js中,定義了Vue的構造方法,具體代碼以下所示:vue

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的構造方法接收一個參數options,options即咱們實例化時定義的包含el,data,components等屬性的對象,實例化時實際只執行vue初始化時已經在構造方法原型上定義的_init方法,_init實際代碼以下所示:node

 Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++
    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    // a flag to avoid this being observed
    vm._isVue = true
    // merge options
    // 合併屬性,判斷初始化的是不是組件
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else { // 合併vue屬性
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      // 初始化proxy攔截器
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    // 初始化組件生命週期標誌位
    initLifecycle(vm)
    // 初始化組件事件偵聽
    initEvents(vm)
    // 初始化渲染方法
    initRender(vm)
    callHook(vm, 'beforeCreate')
    // 初始化依賴注入內容,在初始化data、props以前
    initInjections(vm) // resolve injections before data/props
    // 初始化props/data/method/watch/methods
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')

    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${vm._name} init`, startTag, endTag)
    }
    // 掛載元素
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }

  從上述代碼中,咱們能夠清晰的看到在vue的生命週期每一個階段具體作了什麼事,好比:react

  1. 咱們在beforeCreate中,是訪問不到data數據的,mergeOptions是合併實例和mixins/extend上的數據,返回值vm.$options是合併後實例上的屬性,data數據返回是一個function,由於屬性data的合併策略是返回一個function,博文【淺析vue混入(mixins)】有具體的介紹。
  2. 在created時,咱們並不能訪問DOM對象,由於此時模板文件尚未解析,尚未生成具體的DOM元素,在created以前,只是對組件中的數據進行了初始化,具體的解析template和生成vnode,到生成真實DOM掛載到頁面上,在vm.$mount方法中一步步執行。

  用過vue的都知道,vue是數據驅動的一個框架,實現雙向數據綁定是利用數據劫持,即Object.defineProperty的get和set,在get中進行依賴收集,set中進行派發更新。可是數據是如何初始化的呢?以data爲例,咱們來看下vue是如何進行數據初始化的。web

  如上述代碼,在beforeCreate後,會走進initState方法,initState中,會分別對props,methods,data和watch進行初始化,以下所示:express

export function initState (vm: Component) {
  // 初始化組件的watcher列表
  vm._watchers = []
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
    // 初始化data
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }
  if (opts.computed) initComputed(vm, opts.computed)
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

  咱們暫且值看initData,data在mergeOptions時,返回的是一個function,獲取data數據,須要執行mergeOptions返回數據中的data方法,initData代碼以下所示:數組

function initData (vm: Component) {
  let data = vm.$options.data
  // 獲取到組件上的data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== 'production' && warn(
      'data functions should return an object:\n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    )
  }
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      // 屬性名不能與方法名重複
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    // 屬性名不能與state名稱重複
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) { // 驗證key值的合法性
      // 將_data中的數據掛載到組件vm上,這樣就能夠經過this.xxx訪問到組件上的數據
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  // 響應式監聽data是數據的變化
  observe(data, true /* asRootData */)
}

  getData代碼以下所示:框架

export function getData (data: Function, vm: Component): any {
  // #7573 disable dep collection when invoking data getters
  pushTarget()
  try {
    // 調用在屬性合併時,返回的data
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, `data()`)
    return {}
  } finally {
    popTarget()
  }
}

  這裏面有pushTarget/popTarget,這裏主要是用於保證不管什麼時候,執行的組件監聽計算只有一個,這個具體後面再討論。getData的返回值就是合併後的data對象,賦值到當前的實例屬性。接下來有個while循環,裏面主要作三件事,dom

    第一,判斷咱們聲明的data變量的合法性,咱們聲明變量的名稱必定不要與methods或者props中的屬性名重複,這也是許多新手容易犯的錯誤ide

    第二,聲明變量的時候,不要用以_或者$開頭的變量,這些可能會致使聲明變量和vue私有變量衝突

    第三,將data中的變量代理到vm(組件實例)上,按照this的指向性原理,data對象中的this應該指向data,而不該該指向vm,這裏作了一層封裝代理,具體代碼以下:

// 屬性代理,從一個原對象中拿數據
export function proxy (target: Object, sourceKey: string, key: string) {
  // 設置對象屬性的get/set,將data中的數據代理到組件對象vm上
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

  接下來下一步所須要執行的內容就比較重要了,須要對data對象添加響應式偵聽,調用observe方法,observe方法代碼以下所示:

export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  // 存在__ob__屬性的通常爲觀察者對象的實例
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if ( // Object.isExtensible 判斷對象是不是可擴展的(能夠添加新屬性)
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) { // 必須爲數組 || 對象,才能實例化觀察者對象
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

  每個響應式對象,都會有__ob__屬性,這個是vue中在聲明響應式屬性時定義的,若是沒有該屬性,數據的變化就不會被監測到,其餘的能夠暫時忽略,初始化響應對象是實例化了Observe類,Observer類的具體實現以下所示:

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data

  constructor (value: any) {
    this.value = value
    // 實例化一個發佈-訂閱模型
    this.dep = new Dep()
    this.vmCount = 0
    // 給監聽對象定義一個__ob__屬性,屬性值爲this,指向當前實例
    // 存在該屬性的對象,就是響應式對象
    def(value, '__ob__', this)
    // 數組類型
    if (Array.isArray(value)) {
      // 存在原型 __proto__,重寫數組原型上的方法
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        // 不存在原型,則在數組中複製重寫後的數組方法
        copyAugment(value, arrayMethods, arrayKeys)
      }
      // 響應式監聽數組的變化
      this.observeArray(value)
    } else {
      // 若是值的類型爲Object,則響應式的聲明對象屬性
      this.walk(value)
    }
  }

  在實例化時,有兩個分支,一個是數組,一個是對象,在實例化時,都會數據的中定義__ob__屬性,值爲當前觀察者對象。咱們先看對象的響應式聲明方式,調用this.walk,具體代碼以下:

  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      // 響應式定義對象屬性的get set
      defineReactive(obj, keys[i])
    }
  }

  defineReactive是重點,添加對象屬性的get/set,get和set中進行數據的劫持,實現代碼以下:

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  // 初始化一個發佈-訂閱模型,每一個對象都包含一個dep實例
  const dep = new Dep()
  // 獲取屬性描述符
  const property = Object.getOwnPropertyDescriptor(obj, key)
  // 對象的屬性應該是可擴展、可配置的
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  // 處理obj的值
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  // 若是val值存在Object,則須要偵聽val值的變化
  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      // 依賴收集 @todo
      if (Dep.target) {
        dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      // 派發更新 @todo
      // 獲取到value數據
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 從新更新下數據依賴
      childOb = !shallow && observe(newVal)
      // 通知數據更新???@todo
      dep.notify()
    }
  })
}

  任何數據的讀取,都會走到get方法中,數據的更新,都會走get/set,其中在set中,dep.notify會派發更新頁面數據,具體實現技術細節,在後續文章中,會進行詳細描述。至此,data初始化工做算是完成了,數據的響應式原理核心利用Dep和Watcher兩個類,後面文章專門詳細描述vue的響應式原理及Dep和Watcher對象充當的角色和做用,本篇不作詳細描述。

  數據初始化完成後,接下來須要作的就是解析template和掛載dom,在src\platforms\web\entry-runtime-with-compiler.js中,定義了$mount方法,具體以下所示:

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  // 獲取或查詢元素
  el = el && query(el)

  /* istanbul ignore if */
  // vue 不容許直接掛載到body或頁面文檔上
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && 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
    // 存在template模板,解析vue模板文件
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !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 !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      // 經過選擇器獲取元素內容
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      /**
       *  1.將temmplate解析ast tree
       *  2.將ast tree轉換成render語法字符串
       *  3.生成render方法
       */
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  return mount.call(this, el, hydrating)
}

  從上述方法中,咱們能獲得如下信息:

    一、不要將根元素放到body或者html上

    二、在vue中,能夠在對象中定義template/render或者直接使用template、el表示元素選擇器,用法比較靈活

    三、不管哪一種寫法,最終都會解析成render函數,調用compileToFunctions,會將template解析成render函數

  對template的解析步驟大體分爲如下幾步:

    一、將html文檔片斷解析成ast描述符

    二、將ast描述符解析成字符串

    三、生成render function

  以下圖所示:

  template:

   ast:

   function string

   生成render函數:

   生成render函數,掛載到vm上後,會再次調用mount方法,這個mount方法不是entry-runtime-with-compiler.js複寫的這個,是Vue原型上的方法在src\platforms\web\runtime\index.js中,裏面會調用mountComponent方法,具體以下:

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

  src\core\instance\lifecycle.js

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  // 若是沒有獲取解析的render函數,則會拋出警告
  // render是解析模板文件生成的
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== 'production') {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
        vm.$options.el || el) {
        warn(
          'You are using the runtime-only build of Vue where the template ' +
          'compiler is not available. Either pre-compile the templates into ' +
          'render functions, or use the compiler-included build.',
          vm
        )
      } else {
        // 沒有獲取到vue的模板文件
        warn(
          'Failed to mount component: template or render function not defined.',
          vm
        )
      }
    }
  }
  // 執行beforeMount鉤子
  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 && !vm._isDestroyed) {
        // 數據更新引起的組件更新
        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
}

   這個方法中主要流程是:

    一、調用了beforeMount鉤子函數

    二、定義updateComponent方法,是渲染DOM的入口方法

    三、對vm添加監聽,實例化一個watcher,而後調用updateComponent方法

    四、調用mounted聲明週期鉤子,至此組件實例化結束

  Watcher類以下所示:

export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  lazy: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>;
  newDeps: Array<Dep>;
  depIds: SimpleSet;
  newDepIds: SimpleSet;
  before: ?Function;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    // 是渲染的watcher @todo
    if (isRenderWatcher) {
      vm._watcher = this
    }
    // 將vm添加到組件的_watchers隊列中
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
      this.before = options.before
    } else {
      this.deep = this.user = this.lazy = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.lazy // for lazy watchers
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    // updateComponents
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop
        process.env.NODE_ENV !== 'production' && warn(
          `Failed watching path: "${expOrFn}" ` +
          'Watcher only accepts simple dot-delimited paths. ' +
          'For full control, use a function instead.',
          vm
        )
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }

  /**
   * Evaluate the getter, and re-collect dependencies.
   * 執行更新組件的方法,先將當前要執行的watcher推入到執行隊列中 @todo
   */
  get () {
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // "touch" every property so they are all tracked as
      // dependencies for deep watching
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

  看起來很長,其實主要就是調用在上述第二步聲明的updateComponent方法,updateComponent方法主要執行在vue初始化時聲明的_render,_update方法,其中,_render的做用主要是生成vnode,_update主要功能是調用__patch__,將vnode轉換爲真實DOM,而且更新到頁面中,具體以下:

// 定義vue 原型上的render方法
  Vue.prototype._render = function (): VNode {
    const vm: Component = this
    // render函數來自於組件的option
    const { render, _parentVnode } = vm.$options

    if (_parentVnode) {
      vm.$scopedSlots = normalizeScopedSlots(
        _parentVnode.data.scopedSlots,
        vm.$slots,
        vm.$scopedSlots
      )
    }

    // set parent vnode. this allows render functions to have access
    // to the data on the placeholder node.
    vm.$vnode = _parentVnode
    // render self
    let vnode
    try {
      // There's no need to maintain a stack because all render fns are called
      // separately from one another. Nested component's render fns are called
      // when parent component is patched.
      currentRenderingInstance = vm
      // 調用render方法,本身的獨特的render方法, 傳入createElement參數,生成vNode
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      // return error render result,
      // or previous vnode to prevent render error causing blank component
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {
        try {
          vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
        } catch (e) {
          handleError(e, vm, `renderError`)
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    } finally {
      currentRenderingInstance = null
    }
    // if the returned array contains only a single node, allow it
    if (Array.isArray(vnode) && vnode.length === 1) {
      vnode = vnode[0]
    }
    // return empty vnode in case the render function errored out
    if (!(vnode instanceof VNode)) {
      if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
        warn(
          'Multiple root nodes returned from render function. Render function ' +
          'should return a single root node.',
          vm
        )
      }
      vnode = createEmptyVNode()
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }

  _render返回值: 

   _update:

 Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
    const vm: Component = this
    const prevEl = vm.$el
    const prevVnode = vm._vnode
    // 設置當前激活的做用域
    const restoreActiveInstance = setActiveInstance(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 */)
    } else {
      // updates
      vm.$el = vm.__patch__(prevVnode, vnode)
    }
    restoreActiveInstance()
    // 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's updated hook.
  }

  在掛載DOM的過程當中,是先添加新數據生成的節點,而後再移除老的節點。

相關文章
相關標籤/搜索