Vue源碼之Vue實例初始化

這一節主要記錄一下:Vue 的初始化過程

以下正式開始:

Vue官網的生命週期圖示表

生命週期圖示

重點說一下 new Vue()後的初始化階段,也就是created之前發生了什麼。

初始化流程

initLifecycle 階段

export function initLifecycle (vm: Component) {
  const options = vm.$options

  // locate first non-abstract parent
  let parent = options.parent
  if (parent && !options.abstract) {
    while (parent.$options.abstract && parent.$parent) {
      parent = parent.$parent
    }
    parent.$children.push(vm) // 自己把自己添加到父級的$children數組中
  }

  vm.$parent = parent // 父組件實例
  vm.$root = parent ? parent.$root : vm // 根組件  如果不存在父組件,則本身就是根組件

  vm.$children = [] // 用來存放子組件
  vm.$refs = {}

  vm._watcher = null 
  vm._inactive = null 
  vm._directInactive = false
  vm._isMounted = false
  vm._isDestroyed = false
  vm._isBeingDestroyed = false
}

接下來是initEvents 階段

// v-on如果寫在平臺標籤上如:div,則會將v-on上註冊的事件註冊到瀏覽器事件中
// v-on如果寫在組件標籤上,則會將v-on註冊的事件註冊到子組件的事件系統
// 子組件(Vue實例)在初始化的時候,有可能接收到父組件向子組件註冊的事件。
// 子組件(Vue實例)自身模板註冊的事件,只要在渲染的時候纔會根據虛擬DOM的對比結果
// 來確定是註冊事件還是解綁事件

// 這裏初始化的事件是指父組件在模板中使用v-on註冊的事件添加到子組件的事件系統也就是vue的事件系統。
export function initEvents (vm: Component) {
  vm._events = Object.create(null) // 初始化
  vm._hasHookEvent = false
  // init parent attached events 初初始化腹肌組件添加的事件
  const listeners = vm.$options._parentListeners
  if (listeners) {
    updateComponentListeners(vm, listeners)
  }
}

export function updateComponentListeners (
  vm: Component,
  listeners: Object,
  oldListeners: ?Object
) {
  target = vm
  updateListeners(listeners, oldListeners || {}, add, remove, createOnceHandler, vm)
  target = undefined
}

initjections 階段

export function initInjections (vm: Component) {
  // 自下而上讀取inject
  const result = resolveInject(vm.$options.inject, vm)
  if (result) {
    // 設置爲false 避免defineReactive函數把數據轉換爲響應式
    toggleObserving(false)
    Object.keys(result).forEach(key => {
        defineReactive(vm, key, result[key])
    })
    // 再次更改回來
    toggleObserving(true)
  }
}

export function resolveInject (inject: any, vm: Component): ?Object {
  if (inject) {
    // inject is :any because flow is not smart enough to figure out cached
    const result = Object.create(null)
    // 如果瀏覽器支持Symbol,則使用Reflect.ownkyes(),否則使用Object.keys()
    const keys = hasSymbol
      ? Reflect.ownKeys(inject)
      : Object.keys(inject)

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      // #6574 in case the inject object is observed...
      if (key === '__ob__') continue
      const provideKey = inject[key].from
      let source = vm
      // 當provided注入內容的時候就是把內容注入到當前實例的_provided中
      // 剛開始的時候 source就是實本身,擋在source._provided中找不到對應的值
      // 就會把source設置爲父實例
      // Vue實例化的第一步就是規格化用戶傳入的數據,所以inject不管時數組還是對象
      // 最後都會變成對象
      while (source) {
        if (source._provided && hasOwn(source._provided, provideKey)) {
          result[key] = source._provided[provideKey]
          break
        }
        source = source.$parent
      }
      // 處理默認值的情況
      if (!source) {
        if ('default' in inject[key]) {
          const provideDefault = inject[key].default
          result[key] = typeof provideDefault === 'function'
            ? provideDefault.call(vm)
            : provideDefault
        } else if (process.env.NODE_ENV !== 'production') {
          warn(`Injection "${key}" not found`, vm)
        }
      }
    }
    return result
  }
}

initState 階段

Vue 中,我們經常會用到 propsmethodswatchcomputeddata 。這些狀態在使用前都需要初始化。而初始化的過程正是在 initState 階段完成。

因爲 injects 是在 initState 之前完成,所以可以在 State 中使用 injects

export function initState (vm: Component) {
  vm._watchers = []
  // 獲取到經過初始化的用戶傳進來的options
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.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)
  }
}

initProps

function initProps (vm: Component, propsOptions: Object) {
  const propsData = vm.$options.propsData || {}
  const props = vm._props = {}
  // cache prop keys so that future props updates can iterate using Array
  // instead of dynamic object key enumeration.
  // 緩存props的key值
  const keys = vm.$options._propKeys = []
  const isRoot = !vm.$parent
  // root instance props should be converted
  // 如果不是跟組件則沒必要轉換成響應式數據
  if (!isRoot) {
    // 控制是否轉換成響應式數據
    toggleObserving(false)
  }
  for (const key in propsOptions) {
    keys.push(key)
    // 獲取props的值
    const value = validateProp(key, propsOptions, propsData, vm)
    defineReactive(props, key, value)
    // static props are already proxied on the component's prototype
    // during Vue.extend(). We only need to proxy props defined at
    // instantiation here.
    // 把props代理到Vue實例上來,可以直接通過this.props訪問
    if (!(key in vm)) {
      proxy(vm, `_props`, key)
    }
  }
  toggleObserving(true)
}

initMethods

function initMethods (vm: Component, methods: Object) {
  const props = vm.$options.props
  for (const key in methods) {
    if (process.env.NODE_ENV !== 'production') {
      // 如果key不是一個函數 報錯
      if (typeof methods[key] !== 'function') {
        warn(
          `Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
          `Did you reference the function correctly?`,
          vm
        )
      }
      // 如果props中存在同名的屬性 報錯
      if (props && hasOwn(props, key)) {
        warn(
          `Method "${key}" has already been defined as a prop.`,
          vm
        )
      }
      // isReserved判斷是否以$或_開頭
      if ((key in vm) && isReserved(key)) {
        warn(
          `Method "${key}" conflicts with an existing Vue instance method. ` +
          `Avoid defining component methods that start with _ or $.`
        )
      }
    }
    // 把methods的方法綁定到Vue實例上
    vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
  }
}

initData

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  // isPlainObject監測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
  // 循環data
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      // 如果在methods中存在和key同名的屬性 則報錯
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    // 如果在props中存在和key同名的屬性 則報錯
    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)) {
      // isReserved判斷是否以$或_開頭
      // 代理data,使得可以直接通過this.key訪問this._data.key
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  // 把data轉換爲響應式數據
  observe(data, true /* asRootData */)
}

initComputed

const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
  // $flow-disable-line
  const watchers = vm._computedWatchers = Object.create(null)
  // computed properties are just getters during SSR
  // 判斷是不是服務端渲染
  const isSSR = isServerRendering()

  for (const key in computed) {
    const userDef = computed[key]
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    if (process.env.NODE_ENV !== 'production' && getter == null) {
      warn(
        `Getter is missing for computed property "${key}".`,
        vm
      )
    }
    // 如果不是ssr,則創建Watcher實例
    if (!isSSR) {
      // create internal watcher for the computed property.
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }

    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    // 如果vm不存在key的同名屬性
    if (!(key in vm)) {
      defineComputed(vm, key, userDef)
    } else if (process.env.NODE_ENV !== 'production') {
      if (key in vm.$data) {
        warn(`The computed property "${key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      }
    }
  }
}
sharedPropertyDefinition = {
    enumerable: true,
    cnfigurable: true,
    get: noop,
    set: noop
}
export function defineComputed (
  target: any,
  key: string,
  userDef: Object | Function
) {
  // 如果是服務端渲染,則computed不會有緩存,因爲數據響應式的過程在服務器是多餘的
  const shouldCache = !isServerRendering()
  // createComputedGetter返回計算屬性的getter
  // createGetterInvoker返回userDef的getter
  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    // 當userDef爲一個對象時
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  if (process.env.NODE_ENV !== 'production' &&
      sharedPropertyDefinition.set === noop) {
    sharedPropertyDefinition.set = function () {
      warn(
        `Computed property "${key}" was assigned to but it has no setter.`,
        this
      )
    }
  }
  // 在tearget上定義一個屬性, 屬性名爲key, 屬性描述符爲sharedPropertyDefinition
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

function createComputedGetter (key) {
  return function computedGetter () {
    // 查找是否存在key的Watcher
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      // 如果dirty爲true,則重新計算,否則返回緩存
      if (watcher.dirty) {
        watcher.evaluate()
      }
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  }
}

function createGetterInvoker(fn) {
  return function computedGetter () {
    return fn.call(this, this)
  }
}

initWatch

function initWatch (vm: Component, watch: Object) {
  for (const key in watch) {
    const handler = watch[key]
    // 處理數組類型
    if (Array.isArray(handler)) {
      for (let i = 0; i < handler.length; i++) {
        createWatcher(vm, key, handler[i])
      }
    } else {
      createWatcher(vm, key, handler)
    }
  }
}

function createWatcher (
  vm: Component,
  expOrFn: string | Function,
  handler: any,
  options?: Object
) {
   // isPlainObject檢查是否是對象
  if (isPlainObject(handler)) {
    options = handler
    handler = handler.handler
  }
  if (typeof handler === 'string') {
    handler = vm[handler]
  }
  // 最後調用$watch
  return vm.$watch(expOrFn, handler, options)
}

initProvide階段

export function initProvide (vm: Component) {
  const provide = vm.$options.provide
  if (provide) {
    // 把provided存到_provided上
    vm._provided = typeof provide === 'function'
      ? provide.call(vm)
      : provide
  }
}

到這裏 Vue 的初始化就結束了,接下來就是觸發生命週期函數 created

總結一下:new Vue() 執行之後,Vue 進入初始化階段。

初始化流程如下:

  • 規格化 $options ,也就是用戶自定義的數據
  • initLifecycle 注入生命週期
  • initEvents 初始化事件,注意:這裏的事件是值在父組件在子組件上定義的事件
  • initRender
  • initjections 初始化 jetction
  • initProps 初始化props
  • initState 包括propsmethodsdatacomputedwatch
  • initProvided 初始化 provide
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章