render
vm._render
是在core/instance/render.js
中定义的
/* core/instance/render.js */
export function renderMixin (Vue: Class) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype)
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
Vue.prototype._render = function (): VNode {
const vm: Component = this
const { render, _parentVnode } = vm.$options
// reset _rendered flag on slots for duplicate slot check
if (process.env.NODE_ENV !== 'production') {
for (const key in vm.$slots) {
// $flow-disable-line
vm.$slots[key]._rendered = false
}
}
if (_parentVnode) {
vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode
// render self
let vnode
try {
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
handleError(e, vm, `render`)
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
} catch (e) {
handleError(e, vm, `renderError`)
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
)
}
vnode = createEmptyVNode()
}
// set parent
vnode.parent = _parentVnode
return vnode
}
}
这段代码的核心是render
方法的调用:
vnode = render.call(vm._renderProxy, vm.$createElement)
根据Vue的文档,如下的模版:
{{ message }}
相当于如下的render
函数:
render: function (createElement) {
return createElement('div', {
attrs: {
id: 'app'
},
}, this.message)
}
render
函数的第一个参数是createElement
,也就是调用时传入的vm.$createElement
方法。
vm.$createElement
是在initRender
时被加入到vm实例上的:
export function initRender (vm: Component) {
// ...
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
}
可以看到,实际上调用了定义在core/vdom/create-element.js
中定义的createElement
函数。内部版本vm._c
是用于从模版编译得到的render函数,vm.$createElement
是用于用户手写的render函数,它们的区别就是最后一个参数alwaysNormalize
createElement
createElement
函数参数是:
- tag: 一个 HTML 标签字符串,组件选项对象,或者解析上述任何一种的一个 async 异步函数,必要参数。
- data: 一个包含模板相关属性的数据对象, 可选参数
- children: 子节点(VNodes)或子节点的Array, 或使用字符串来生成“文本节点”。可选参数
由于可选参数的存在,createElement
函数先对参数做了处理,然后调用真正的_createElement
函数
export function _createElement (
context: Component,
tag?: string | Class | Function | Object,
data?: VNodeData,
children?: any,
normalizationType?: number
): VNode | Array {
if (isDef(data) && isDef((data: any).__ob__)) {
// process.env.NODE_ENV !== 'production' && warn(
// `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
// 'Always create fresh vnode data objects in each render!',
// context
// )
return createEmptyVNode()
}
// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
tag = data.is
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// warn against non-primitive key
if (process.env.NODE_ENV !== 'production' &&
isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
if (!__WEEX__ || !('@binding' in data.key)) {
warn(
'Avoid using non-primitive value as key, ' +
'use string/number value instead.',
context
)
}
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {}
data.scopedSlots = { default: children[0] }
children.length = 0
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children)
}
let vnode, ns
if (typeof tag === 'string') {
let Ctor
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
)
} else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag)
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
)
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children)
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
if (isDef(ns)) applyNS(vnode, ns)
if (isDef(data)) registerDeepBindings(data)
return vnode
} else {
return createEmptyVNode()
}
}
这段代码的核心逻辑一个是childeren
的normalize
, 另一个是VNode的创建。
Normalize
根据render函数是编译生成还是用户手写,分别调用了simpleNormalizeChildren
和normalizeChildren
这两个函数定义在core/vdom/helpers/normalize-children.js
中
export function simpleNormalizeChildren (children: any) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
理论上编译生成的 children 都已经是 VNode 类型的,但这里有一个例外,就是 functional component 函数式组件返回的是一个数组而不是一个根节点,所以simpleNormalizeChildren
会将children数组flatten到只有一层
export function normalizeChildren (children: any): ?Array {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
如果children是基础类型,会创建一个文本节点,返回只包含这个文本节点的Array,否则调用normalizeArrayChildren
。
一些情况下children会包含嵌套数组,比如模版里有,
或者用户手写的render函数。 normalizeArrayChildren
会展开children中的嵌套数组,使children只有一层。
同时如果遇到连续的多个文本节点,normalizeArrayChildren
会把它们合并成一个文本节点。
创建VNode
如果根节点tag
是HTML标签,那么用
vnode = new VNode(
tag, data, children,
undefined, undefined, context
)
创建一个VNode实例
如果根节点是一个组件那么调用createComponent
创建组件的VNode
/* core/vdom/create-component.js */
export function createComponent (
Ctor: Class | Function | Object | void,
data: ?VNodeData,
context: Component,
children: ?Array,
tag?: string
): VNode | Array | 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)
}
...
data = data || {}
...
// 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
...
// 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
)
...
return vnode
}
首先创建组件的构造函数,Ctor = baseCtor.extend(Ctor)
,这里的baseCtor
就是Vue
的构造函数,然后提取data
里的事件监听器。通过installComponentHooks
安装init
,prepatch
,insert
,destroy
这些钩子函数,添加到data.hook
。最后用
const vnode = new VNode(
`vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
data, undefined, undefined, undefined, context,
{ Ctor, propsData, listeners, tag, children },
asyncFactory
)
创建组件的VNode,{ Ctor, propsData, listeners, tag, children }
是作为组件的componentOpotions
,那么组件的VNode与普通元素的VNode相比大致上就是多了componentOptions
这个属性和data
中的hook
属性