您的位置:首页技术文章
文章详情页

Vue初始化中的选项合并之initInternalComponent详解

【字号: 日期:2023-01-13 17:08:06浏览:47作者:猪猪

今天给大家分享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._parentVnodeopts.parent = options.parentopts._parentVnode = parentVnode

接下把传入参数的option的_parentVode和parent挂载到组件实例$options上。用我们在两种策略里的那个例子来说,parent就是我们组件的根实例,而_parentVnode就是<comp :msg='msg' @log-msg='logMsg'></comp>生成的一个Vnode对象。

const vnodeComponentOptions = parentVnode.componentOptionsopts.propsData = vnodeComponentOptions.propsDataopts._parentListeners = vnodeComponentOptions.listenersopts._renderChildren = vnodeComponentOptions.childrenopts._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初始化选项合并内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Vue
相关文章: