借用vue.js官网的图来解释组件,如下:
组件渲染的一个简单例子:
// App
<template>
<div id="app">Hello App!</div>
</template>
// js
const app = new Vue({
el: "#app",
render(h) {
return h(App);
},
});
得到视图:
Hello App!
组件渲染的流程部分和模板渲染的相同,可以参考链接:juejin.cn/post/712858…
组件的渲染和模板渲染的主流程基本一致,都是:
- 将模板转换成render函数
- 将render函数转换成虚拟DOM
- 将虚拟DOM进行视图渲染
1、模板转换成render函数
该过程使用过程中由可以由vue-loader实现,www.npmjs.com/package/vue…
最终结果为包含render函数的对象:
2、实例化vNode
_createElement方法中,在模板渲染过程中使用tag做判断符合typeof tag === 'string'执行的是普通模板的虚拟DOM构建;在组件渲染过程中则是else逻辑,执行逻辑为:
// direct component options / constructor
vnode = createComponent(tag, data, context, children)
createComponent函数:
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
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor)
}
// if at this stage it's not a constructor or an async component factory,
// reject.
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(`Invalid Component definition: ${String(Ctor)}`, context)
}
return
}
// async component
let asyncFactory
if (isUndef(Ctor.cid)) {
asyncFactory = Ctor
Ctor = resolveAsyncComponent(asyncFactory, baseCtor)
if (Ctor === undefined) {
// return a placeholder node for async component, which is rendered
// as a comment node but preserves all the raw information for the node.
// the information will be used for async server-rendering and hydration.
return createAsyncPlaceholder(
asyncFactory,
data,
context,
children,
tag
)
}
}
data = data || {}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor)
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data)
}
// extract props
const propsData = extractPropsFromVNodeData(data, Ctor, tag)
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
const listeners = data.on
// replace with listeners with .native modifier
// so it gets processed during parent component patch.
data.on = data.nativeOn
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners & slot
// work around flow
const slot = data.slot
data = {}
if (slot) {
data.slot = slot
}
}
// install component management hooks onto the placeholder node
installComponentHooks(data)
// return a placeholder vnode
const name = Ctor.options.name || tag
const vnode = new VNode(
`vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
data, undefined, undefined, undefined, context,
{ Ctor, propsData, listeners, tag, children },
asyncFactory
)
// Weex specific: invoke recycle-list optimized @render function for
// extracting cell-slot template.
// https://github.com/Hanks10100/weex-native-directive/tree/master/component
/* istanbul ignore if */
if (__WEEX__ && isRecyclableComponent(vnode)) {
return renderRecyclableComponentTemplate(vnode)
}
return vnode
}
看着挺多,主要三件事,通过Vue的extend方法构建构造函数,通过installComponentHooks安装构造函数,最后把拼接的参数传给虚拟DOM的构造函数进行虚拟DOM的实例化。
(1)构造函数
const baseCtor = context.$options._base中的baseCtor是Vue构造函数,该变量是initGlobalAPI(Vue)的时候完成通过Vue.options._base = Vue完成,在initGlobalAPI(Vue)中还通过initExtend(Vue)完成了extend方法的初始化:
Vue.extend = function (extendOptions: Object): Function {
extendOptions = extendOptions || {}
const Super = this
const SuperId = Super.cid
const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
const name = extendOptions.name || Super.options.name
if (process.env.NODE_ENV !== 'production' && name) {
validateComponentName(name)
}
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
)
Sub['super'] = Super
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps(Sub)
}
if (Sub.options.computed) {
initComputed(Sub)
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend
Sub.mixin = Super.mixin
Sub.use = Super.use
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type]
})
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options
Sub.extendOptions = extendOptions
Sub.sealedOptions = extend({}, Sub.options)
// cache constructor
cachedCtors[SuperId] = Sub
return Sub
}
其中,cachedCtors[SuperId] = Sub进行缓存,如果存在直接进行return cachedCtors[SuperId]。
如果不存在,首先定义构造函数const Sub = function VueComponent (options) { this._init(options) },使得Sub也拥有Vue中init的能力。然后,通过原型继承的方式将Vue构造函数中原型上的方法和属性挂载到Sub上Sub.prototype = Object.create(Super.prototype),使得Sub原型上拥有Vue原型上的能力,此时,Sub实例的构造函数还Vue,通过Sub.prototype.constructor = Sub的方式指回Sub。并通过Sub.options = mergeOptions( Super.options, extendOptions )将Vue构造函数上的options和extendOptions进行合并,同时,在Sub上通过给对象添加属性的方式给Sub中将Vue中重要的属性直接挂在到Sub对象上(函数也是对象)。
整个过程中可以看出,Sub通过借助函数Vue的方法init,原型挂载和属性赋值的方式拥有Vue函数上的能力。
(2)安装钩子函数
安装钩子函数的目的是在组件patch的不同节点执行不同的方法,并且已经在data.hook中已经拥有的钩子函数,也可以通过mergeHook(f1,f2)进行合并,在执行过程中依次执行。
function installComponentHooks (data: VNodeData) {
const hooks = data.hook || (data.hook = {})
for (let i = 0; i < hooksToMerge.length; i++) {
const key = hooksToMerge[i]
const existing = hooks[key]
const toMerge = componentVNodeHooks[key]
if (existing !== toMerge && !(existing && existing._merged)) {
hooks[key] = existing ? mergeHook(toMerge, existing) : toMerge
}
}
}
function mergeHook (f1: any, f2: any): Function {
const merged = (a, b) => {
// flow complains about extra args which is why we use any
f1(a, b)
f2(a, b)
}
merged._merged = true
return merged
}
其中componentVNodeHooks的定义如下:
// inline hooks to be invoked on component VNodes during patch
const componentVNodeHooks = {
init (vnode: VNodeWithData, hydrating: boolean): ?boolean {
// ...
},
prepatch (oldVnode: MountedComponentVNode, vnode: MountedComponentVNode) {
// ...
},
insert (vnode: MountedComponentVNode) {
// ...
},
destroy (vnode: MountedComponentVNode) {
// ...
}
}
(3)返回vNode
const vnode = new VNode(
`vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
data, undefined, undefined, undefined, context,
{ Ctor, propsData, listeners, tag, children },
asyncFactory
)
将相关参数传入到构造函数VNode中实例化产生vNode,并返回。
3、组件patch
在组件patch的过程中会执行createElm方法
// create new node
createElm(
vnode,
insertedVnodeQueue,
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
在当前例子中vnode指的是组件虚拟DOM,parentElm指的是BODY节点,createElm方法中如果是组件渲染则执行if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return }的逻辑,createComponent函数如下:
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
let i = vnode.data
if (isDef(i)) {
const isReactivated = isDef(vnode.componentInstance) && i.keepAlive
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */)
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue)
insert(parentElm, vnode.elm, refElm)
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)
}
return true
}
}
}
这里也主要做了三件事,执行钩子函数init,初始化组件initComponent,将组件中的节点插入到父组件中
(1)执行钩子函数init
组件渲染过程中,i(vnode, false /* hydrating */)中的i指的是钩子函数init,
init (vnode: VNodeWithData, hydrating: boolean): ?boolean {
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// kept-alive components, treat as a patch
const mountedNode: any = vnode // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode)
} else {
const child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance
)
child.$mount(hydrating ? vnode.elm : undefined, hydrating)
}
},
其中,createComponentInstanceForVnode的目的是实例化组件的构造函数,并执行当前构造函数中的this._init初始化方法进行初始化操作,最后,在方法this._init中执行if (vm.$options.el) { vm.$mount(vm.$options.el); }过程中没有vm.$options.el挂载节点。组件实例则通过child.$mount(hydrating ? vnode.elm : undefined, hydrating)进行组件的挂载,当执行到vm._update(vm._render(), hydrating)时,渲染逻辑和模板渲染基本相同,并在vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)的时候,将渲染完成的节点赋值给vm.$el上,即赋值在了vnode.componentInstance上。
(2)初始化组件initComponent
function initComponent (vnode, insertedVnodeQueue) {
if (isDef(vnode.data.pendingInsert)) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
vnode.data.pendingInsert = null
}
vnode.elm = vnode.componentInstance.$el
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode)
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode)
}
}
vnode.elm = vnode.componentInstance.$el将当前实例中渲染完成的$el赋值给vnode中。
(3)组件vNode中的节点插入到父节点
insert(parentElm, vnode.elm, refElm),例子中的parentElm则是BODY节点,如果是复杂的组件嵌套,parentElm则是当前实例的父组件,整个过程将是递归的过程,insert方法就是父组件节点和子组件节点桥梁。
小结:组件渲染和模板渲染都是获取vNode并进行vNode的渲染;但是,组件获取vNode是通过
vnode = createComponent(tag, data, context, children),组件渲染主要是通过执行钩子函数init并让组件实例通过$mount实现节点渲染。