從Vue源碼的角度解析面試題[一]

經(jīng)常見到有人問看某某某源碼有沒有用,從我個(gè)人的經(jīng)歷來(lái)說(shuō)(雖然我的經(jīng)歷也不長(zhǎng)),我覺得是很有用的,而且非常有用??匆恍┛蚣芎蛶?kù)的源碼可以讓我們了解到其中的某些特性是怎么實(shí)現(xiàn)的,使我們對(duì)這些技術(shù)更加熟悉;另一方面,看源碼的過(guò)程也是個(gè)學(xué)習(xí)的過(guò)程,你可以學(xué)習(xí)整個(gè)項(xiàng)目的架構(gòu),學(xué)習(xí)作者的思路,學(xué)習(xí)某個(gè)函數(shù)的實(shí)現(xiàn),或者代碼風(fēng)格等等,因?yàn)楹芏鄸|西是自己無(wú)論如何也想不到的,所以我們可以從一些優(yōu)秀的項(xiàng)目的源碼中去學(xué)習(xí)、去借鑒,然后應(yīng)用到自己的代碼里,這樣就會(huì)潛移默化的提升自己的能力,我覺得這比知道某些功能是怎么實(shí)現(xiàn)的要更加重要。

其實(shí)我也一直想寫一些 Vue 源碼分析的文章,但是現(xiàn)在網(wǎng)上分析 Vue 源碼的文章隨便都能找出來(lái)百八十篇,實(shí)在是太多了,我也不想再重復(fù)去寫那么多。所以我想了個(gè)辦法,找一些面試題,從源碼的角度來(lái)分析,這樣既能多看幾道面試題,又能鞏固源碼的學(xué)習(xí),豈不是一舉兩得,所以我打算每周找?guī)讉€(gè) Vue 面試題來(lái)分析下,希望各位小伙伴們看完能有一點(diǎn)收獲。

由于通過(guò)面試題分析的話并不會(huì)從頭去看源碼,而且我也不會(huì)寫的特別細(xì)致,所以本文章適合有基礎(chǔ)的同學(xué)看,否則某些地方可能看不太明白。我這些分析只是輔助,還是建議大家有時(shí)間的話能完整的看一看源碼,畢竟多看優(yōu)秀的項(xiàng)目才能提升自己的代碼能力,那廢話不多說(shuō),我們開始看題吧。

在使用計(jì)算屬性時(shí),函數(shù)名和 data 數(shù)據(jù)源中的數(shù)據(jù)可以同名嗎?

答案: 不可以重名,不僅僅是計(jì)算屬性和 data,其他的如 props,methods 都不可以重名,因?yàn)?Vue 會(huì)把這些屬性掛載在組件實(shí)例上,直接使用 this 就可以訪問,如果重名就會(huì)導(dǎo)致沖突。

源碼分析
在組件初始化的時(shí)候會(huì)執(zhí)行_init 函數(shù)

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)
    }

    vm._isVue = true
    // merge options
    if (options && options._isComponent) {
      console.log('_isComponent',options)
      // 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 {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vmnext
    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')

    /* 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)
    }
  }
}

這里面執(zhí)行了一個(gè) initState 的方法,這個(gè)方法就是初始化數(shù)據(jù)的關(guān)鍵方法

export function initState(vm: Component) {
  vm._watchers = []
  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)
  }
}

可以看到這里初始化了很多數(shù)據(jù),有 props,methods,data,computed,watch 這幾個(gè)。對(duì)于上面這個(gè)問題,我們只看 initComputed 這個(gè)方法

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)
    }

    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.
    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)
      }
    }
  }
}

在這個(gè)方法的最底部,做了一個(gè)判斷,回去查你定義的 computed 的 key 值在 data 和 props 中有沒有存在,這個(gè)時(shí)候 props 和 data 都已經(jīng)初始化完成了,且已經(jīng)掛載到了組件實(shí)例上,你的 computed 如果有沖突的話就會(huì)報(bào)錯(cuò)了,其實(shí)這幾個(gè)初始化數(shù)據(jù)的方法內(nèi)部都有做這些檢測(cè)。

怎么給 vue 定義全局的方法?

答案:目前一般有兩種做法:一是給直接給 Vue.prototype 上添加,另外一個(gè)是通過(guò) Vue.mixin 注冊(cè)。但是為什么 prototype 和 mixin 里面的方法可以在組件訪問到呢?

源碼:由于這里牽扯的比較多,我只說(shuō)關(guān)鍵點(diǎn),可能不是很詳細(xì),希望各位小伙伴們有時(shí)間自己去看一下。
我們都知道 Vue 內(nèi)部很多操作都是通過(guò)虛擬節(jié)點(diǎn)進(jìn)行的,在初始化時(shí)候會(huì)執(zhí)行創(chuàng)建虛擬節(jié)點(diǎn)的操作,這個(gè)就是通過(guò)一個(gè)叫 createElement 的函數(shù)進(jìn)行的,就是渲染函數(shù)的第一個(gè)參數(shù),在 createElement 內(nèi)如果發(fā)現(xiàn)一個(gè)節(jié)點(diǎn)是組件的話,會(huì)執(zhí)行 createComponent 函數(shù)

export function createComponent(
  Ctor: Class<Component> | Function | Object | void,
  data: ?VNodeData,
  context: Component,
  children: ?Array<VNode>,
  tag?: string
): VNode | Array<VNode> | void {
  if (isUndef(Ctor)) {
    return
  }

  //省略其他邏輯...
  // ......
  const baseCtor = context.$options._base
  if (isObject(Ctor)) {
    Ctor = baseCtor.extend(Ctor)
  }

  // ......
}

這里是創(chuàng)建了一個(gè)組件的構(gòu)造函數(shù),baseCtor 是 Vue 的構(gòu)造函數(shù),其實(shí)下面執(zhí)行的就是 Vue.extend()方法,這個(gè)方法是 Vue 構(gòu)造函數(shù)上的一個(gè)靜態(tài)方法,應(yīng)該有不少小伙伴都用過(guò)這個(gè)方法,我們來(lái)看下這個(gè)方法做了什么事情

/**
 * Class inheritance
 */
Vue.extend = function(extendOptions: Object): Function {
  //省略其他邏輯...
  // ......
  const Sub = function VueComponent(options) {
    this._init(options)
  }
  Sub.prototype = Object.create(Super.prototype)
  Sub.prototype.constructor = Sub
  Sub.cid = cid++
  Sub.options = mergeOptions(Super.options, extendOptions)
  // ......
}

創(chuàng)建了一個(gè) Sub 函數(shù),并且繼承了將 prototype 指向了Object.create(Super.prototype),是 js 里一個(gè)典型的繼承方法,要知道,最終組件的實(shí)例化是通過(guò)這個(gè) Sub 構(gòu)造函數(shù)進(jìn)行的,在組件實(shí)例內(nèi)訪問一個(gè)屬性的時(shí)候,如果本實(shí)例上沒有的話,會(huì)通過(guò)原型鏈向上去查找,這樣我們就可以在組件內(nèi)部訪問到 Vue 的原型。

那么 mixin 是怎么實(shí)現(xiàn)的呢?其實(shí)上面這段代碼還有一個(gè)是 mergeOptions 的操作,這個(gè) mergeOptions 函數(shù)做的事情是將兩個(gè) options 合并在一起,這里我就不展開說(shuō)了,因?yàn)槔锩娴臇|西比較多。這里其實(shí)就是把 Super.options 和我們傳入的 options 合并在一起,這個(gè) Super 的 options 其實(shí)也就是 Vue 的 options,在我們使用 Vue.mixin 這個(gè)方法的時(shí)候,會(huì)把我們傳入的 options 添加到 Vue.options 上

export function initMixin(Vue: GlobalAPI) {
  Vue.mixin = function(mixin: Object) {
    this.options = mergeOptions(this.options, mixin)
    return this
  }
}

這樣 Vue.options 上就會(huì)有我們添加到屬性了,在 extend 的時(shí)候這個(gè)屬性也會(huì)擴(kuò)展到組件構(gòu)造函數(shù)的 options 上,

然后在組件初始化的時(shí)候,會(huì)執(zhí)行 init 方法:

Vue.prototype._init = function(options?: Object) {
  //省略其他邏輯
  // ......
  // 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 {
    vm.$options = mergeOptions(
      resolveConstructorOptions(vm.constructor),
      options || {},
      vm
    )
  }
  // ......
}

里面判斷到是組件時(shí)會(huì)執(zhí)行 initInternalComponent 這個(gè)方法

export function initInternalComponent(
  vm: Component,
  options: InternalComponentOptions
) {
  const opts = (vm.$options = Object.create(vm.constructor.options))
  // doing this because it's faster than dynamic enumeration.
  const parentVnode = options._parentVnode
  opts.parent = options.parent // 父Vnode,activeInstance
  opts._parentVnode = parentVnode // 占位符Vnode
  opts._parentElm = options._parentElm
  opts._refElm = options._refElm

  const vnodeComponentOptions = parentVnode.componentOptions // componentOptions是createComponent時(shí)候傳入new Vnode()的
  opts.propsData = vnodeComponentOptions.propsData
  opts._parentListeners = vnodeComponentOptions.listeners
  opts._renderChildren = vnodeComponentOptions.children
  opts._componentTag = vnodeComponentOptions.tag

  if (options.render) {
    opts.render = options.render
    opts.staticRenderFns = options.staticRenderFns
  }
}

這里又通過(guò)const opts = vm.$options = Object.create(vm.constructor.options)將組件構(gòu)造函數(shù)的 options 賦值給了 vm.$options,這里的vm.constructor.options就是剛才和 Vue.options 合并后的組件構(gòu)造函數(shù)上的 options,這樣我們就在組件內(nèi)部拿到了 Vue.mixin 定義的方法。

Vue 中怎么重置 data

答案:使用 Object.assign(this.$data, this.$options.data())即可。很多人都用過(guò)這個(gè)方法,在網(wǎng)上查到的也都是這個(gè)方法,那么這個(gè)方法的原理是什么,為什么這樣寫能達(dá)到效果呢?

源碼
這個(gè)方法就是一個(gè)簡(jiǎn)單的對(duì)象合并的方法,我們都知道this.$options.data()就是在組件內(nèi)部書寫的 data 函數(shù),執(zhí)行這個(gè)函數(shù)就會(huì)返回一份初始的 data 數(shù)據(jù),那這個(gè)$data 是個(gè)什么呢,它是在什么時(shí)候定義的呢?其實(shí)第一題里面也說(shuō)過(guò)在初始化的時(shí)候執(zhí)行了一個(gè)叫做 initState 的方法,里面又執(zhí)行了 initData 來(lái)初始化數(shù)據(jù):

function initData(vm: Component) {
  let data = vm.$options.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)
      }
    }
    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)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}

我們可以看到這個(gè)方法在最開始執(zhí)行了 data 函數(shù),然后又把返回值賦值給了 vm._data,在函數(shù)的最后又執(zhí)行了proxy(vm,_data, key),我們來(lái)看下 proxy 方法:

export function proxy(target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter() {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter(val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

這個(gè)方法就是通過(guò)Object.defineProperty執(zhí)行了一層代理,這樣我們?cè)诮M件內(nèi)部訪問一個(gè)屬性時(shí),比如 this.name 其實(shí)訪問的是 this._data.name。到這肯定會(huì)有小伙伴有疑問:上面那個(gè)答案是$data,而這里是_data,這是怎么回事呢?

其實(shí)在 Vue 這個(gè)構(gòu)造函數(shù)初始化的時(shí)候還執(zhí)行了一個(gè)方法

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)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

這里是 Vue 構(gòu)造函數(shù)初始化的過(guò)程,我們看下這個(gè) stateMixin 方法,

export function stateMixin(Vue: Class<Component>) {
  // flow somehow has problems with directly declared definition object
  // when using Object.defineProperty, so we have to procedurally build up
  // the object here.
  const dataDef = {}
  dataDef.get = function() {
    return this._data
  }
  const propsDef = {}
  propsDef.get = function() {
    return this._props
  }
  if (process.env.NODE_ENV !== 'production') {
    dataDef.set = function(newData: Object) {
      warn(
        'Avoid replacing instance root $data. ' +
          'Use nested data properties instead.',
        this
      )
    }
    propsDef.set = function() {
      warn(`$props is readonly.`, this)
    }
  }
  Object.defineProperty(Vue.prototype, '$data', dataDef)
  Object.defineProperty(Vue.prototype, '$props', propsDef)
  // 省略其他邏輯...
  //......
}

這里定義了一個(gè) dataDef,dataDef 的 get 方法返回了_data,又通過(guò)Object.defineProperty將$data指向了dataDef,這樣我們?cè)L問 $data 的時(shí)候其實(shí)訪問的是_data,而_data 里保存的就是最終的 data 數(shù)據(jù),所以我們才可以使用Object.assign(this.$data, this.$options.data())來(lái)達(dá)到重置數(shù)據(jù)的目的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容