1. 程式人生 > 程式設計 >Vue初始化中的選項合併之initInternalComponent詳解

Vue初始化中的選項合併之initInternalComponent詳解

今天給大家分享Vue初始化中的選項合併之initInternalComponent的相關知識,具體程式碼如下所示:

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
 opts._parentVnode = parentVnode

 const vnodeComponentOptions = parentVnode.componentOptions
 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
 }
}

initInternalComponent方法接受兩個引數,第一個引數是元件例項,即this。第二個引數是元件建構函式中傳入的option,這個option根據上文的分析,他是在createComponentInstanceForVnode方法中定義的:

export function createComponentInstanceForVnode (
 vnode: any,// we know it's MountedComponentVNode but flow doesn't
 parent: any,// activeInstance in lifecycle state
): Component {
 const options: InternalComponentOptions = {
  _isComponent: true,_parentVnode: vnode,parent
 }
 // check inline-template render functions
 const inlineTemplate = vnode.data.inlineTemplate
 if (isDef(inlineTemplate)) {
  options.render = inlineTemplate.render
  options.staticRenderFns = inlineTemplate.staticRenderFns
 }
 return new vnode.componentOptions.Ctor(options)
}

option中有三個屬性值,_isComponent上面已經提到過了;_parentVode其實就是該元件例項的vnode物件(createComponentInstanceForVnode就是根據這個vnode物件去建立一個元件例項);parent則是該元件的父元件例項物件。
然後我們來看看具體initInternalComponent做了什麼操作:

const opts = vm.$options = Object.create(vm.constructor.options)

首先,用Object.create這個函式,把元件建構函式的options掛載到vm.$options__proto__

上。

const parentVnode = options._parentVnode
opts.parent = options.parent
opts._parentVnode = parentVnode

接下把傳入引數的option的_parentVodeparent掛載到元件例項$options上。用我們在兩種策略裡的那個例子來說,parent就是我們元件的根例項,而_parentVnode就是<comp :msg="msg" @log-msg="logMsg"></comp>生成的一個Vnode物件。

const vnodeComponentOptions = parentVnode.componentOptions
opts.propsData = vnodeComponentOptions.propsData
opts._parentListeners = vnodeComponentOptions.listeners
opts._renderChildren = vnodeComponentOptions.children
opts._componentTag = vnodeComponentOptions.tag

然後把父元件裡的vnode上的四個屬性掛載到我們的$options上,還是用那個例子來說,propsData就是根據:msg="msg"生成的,他的值就是在根元件裡定義的那個msg{msg: "props-message"}。而_parentListeners就是根據@log-msg="logMsg"生成的,他的值是logMsg這個定義在父元件中的方法。

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

最後就是如果傳入的option中如果有render,把render相關的也掛載到$options上。
因此,這個initInternalComponent主要做了兩件事情:1.指定元件$options原型,2.把元件依賴於父元件的props、listeners也掛載到options上,方便子元件呼叫。

總結

到此這篇關於Vue初始化中的選項合併之initInternalComponent詳解的文章就介紹到這了,更多相關Vue初始化選項合併內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!