本文已参与「新人创作礼」活动,一起开启掘金创作之路。
接上一节 new Vue() 数据如何渲染到页面,以超简单代码为例2,继续分析new Vue()过程:
<div id="app">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
上一节分析到该执行updateComponent函数了,贴源码:
updateComponent = () => {
// 第二个参数是false,这里的vm是Vue
vm._update(vm._render(), hydrating)
}
Vue._render()
开始执行updateComponent,其实就是执行了Vue._update(Vue._render(), false),看上去很简单的一行代码,我们继续分析,首先是执行Vue._render(),这个函数是干什么的?上源码,定义在src/core/instance/render.js中:
export function renderMixin (Vue: Class<Component>) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype)
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
// 看!在这儿
Vue.prototype._render = function (): VNode {
// 这儿是Vue
const vm: Component = this
// 取出render函数,这个是之前使用template编译而生成的
const { render, _parentVnode } = vm.$options
// reset _rendered flag on slots for duplicate slot check
// 插槽slot相关逻辑 跳过
if (process.env.NODE_ENV !== 'production') {
for (const key in vm.$slots) {
// $flow-disable-line
vm.$slots[key]._rendered = false
}
}
// 插槽slot相关逻辑 跳过
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 {
// 开始try了,执行编译生成的render函数,vm._renderProxy这儿是Vue,这儿最终生成了vnode
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
// 如果生成的vnode不对,是个数组,报错
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
// 这儿的Vue是根,他没有爸爸
vnode.parent = _parentVnode
// 返回生成的vnode
return vnode
}
}
Vue._render函数最终是要调用render函数生成vnode,就是虚拟节点,虚拟节点是纯js,计算起来比操作Dom要快很多。
vnode = render.call(vm._renderProxy, vm.$createElement)
等同于
vnode = render.call(Vue, Vue.$createElement)
render函数的使用方法,vue的官网有介绍,举个例子,如下代码的template最终被转化成了render函数:
<template> Hello World </template> // 编译成render render(createElement) { return createElement('div', null, "Hello World") }
所以最终就是调用了createElement函数返回vnode,继续分析这儿的Vue.$createElement,源码在src/core/instance/render.js中:
createElement
import { createElement } from '../vdom/create-element'
function initRender (vm) {
......
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
......
}
我们继续找源码:src/core/vdom/create-element.js
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
export function createElement (
context: Component,
tag: any,
data: any,
children: any,
normalizationType: any,
alwaysNormalize: boolean
): VNode | Array<VNode> {
// 类似参数重载,将传入的参数规范化后再执行后面的逻辑
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children
children = data
data = undefined
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE
}
return _createElement(context, tag, data, children, normalizationType)
}
这儿对传入的参数进行了判断,做了规范化,将传入的参数规范化后再执行后面的逻辑,最终调用函数_createElement:
export function _createElement (
context: Component,
tag?: string | Class<Component> | Function | Object,
data?: VNodeData,
children?: any,
normalizationType?: number
): VNode | Array<VNode> {
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
}
// 本次我们传入的tag是'div'
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
}
// 这儿的逻辑是将children参数规范化,使其统一格式
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children)
}
let vnode, ns
// tag是'div',进入逻辑
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
)
// 判断当前实例上的options.components中是否存在该标签,渲染组件节点的逻辑
} else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag)
} else {
// 本次进入这个逻辑,new了一个vnode出来
// 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)
// 返回vnode
return vnode
} else {
return createEmptyVNode()
}
}
从上面代码可以看出,createElement函数的主要逻辑就是将传入的children参数规范化,然后根据VNode类,生成了一个vnode节点,最终返回这个vnode。
1.规范化children
包括两种情况:
1.函数式组件规范化:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
// 当子参数包含组件时——因为是函数式组件可能返回一个数组而不是单个根。在这种情况下,只需要简单的
// 标准化——如果任何子参数是一个数组,我们使用Array.prototype.concat将整个数组平整化。
// 它保证只有1级深度因为函数式组件已经规范化了它们自己的子组件。
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
}
2.嵌套或手写render规范化
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
// 2。当子数组包含总是生成嵌套数组的构造时,
// 例如:<template>, <slot>, v-for,或者当子节点由用户用手写的渲染函数/ JSX提供时。
// 在这种情况下,需要完全的规范化来满足所有可能类型的子值。
export function normalizeChildren(children: any): ?Array<VNode> {
// 如果是原生类型,直接创建文本节点,否则判断是数组的话,执行normalizeArrayChildren函数
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
/**
* Check if value is primitive
*/
export function isPrimitive (value: any): boolean %checks {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
const res = []
let i, c, lastIndex, last
// 遍历children
for (i = 0; i < children.length; i++) {
c = children[i]
if (isUndef(c) || typeof c === 'boolean') continue
lastIndex = res.length - 1
last = res[lastIndex]
// nested
if (Array.isArray(c)) {
// 如果子元素是数组且长度大于0,递归调用normalizeArrayChildren
if (c.length > 0) {
c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`)
// merge adjacent text nodes
// 这儿做了一个优化,如果子元素的第一个与res的最后一个值都是文本节点,则合并为一个节点
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
c.shift()
}
res.push.apply(res, c)
}
} else if (isPrimitive(c)) {
// 如果是基础属性值且为res的最后一个值为文本节点,将这个值合并到res的最后一个节点上去
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c)
} else if (c !== '') {
// 如果是基础属性值且res的最后一个值不为文本节点,创建一个文本节点推入res中
// convert primitive to vnode
res.push(createTextVNode(c))
}
} else {
// 如果是文本节点,且res的最后一个值也为文本节点,这两个节点合并成一个节点
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text)
} else {
// default key for nested array children (likely generated by v-for)
// 嵌套数组的默认key值
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = `__vlist${nestedIndex}_${i}__`
}
// 推入res
res.push(c)
}
}
}
return res
}
其实这两个函数主要作用就是将createElement的第三个参数,针对在不同情况生成的children,进行规范化处理,为生成vnode而提供规范的参数。
2.VNode类
export default class VNode {
tag: string | void;
data: VNodeData | void;
children: ?Array<VNode>;
text: string | void;
elm: Node | void;
ns: string | void;
context: Component | void; // rendered in this component's scope
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
componentInstance: Component | void; // component instance
parent: VNode | void; // component placeholder node
// strictly internal
raw: boolean; // contains raw HTML? (server only)
isStatic: boolean; // hoisted static node
isRootInsert: boolean; // necessary for enter transition check
isComment: boolean; // empty comment placeholder?
isCloned: boolean; // is a cloned node?
isOnce: boolean; // is a v-once node?
asyncFactory: Function | void; // async component factory function
asyncMeta: Object | void;
isAsyncPlaceholder: boolean;
ssrContext: Object | void;
fnContext: Component | void; // real context vm for functional nodes
fnOptions: ?ComponentOptions; // for SSR caching
fnScopeId: ?string; // functional scope id support
constructor (
tag?: string,
data?: VNodeData,
children?: ?Array<VNode>,
text?: string,
elm?: Node,
context?: Component,
componentOptions?: VNodeComponentOptions,
asyncFactory?: Function
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = undefined
this.context = context
this.fnContext = undefined
this.fnOptions = undefined
this.fnScopeId = undefined
this.key = data && data.key
this.componentOptions = componentOptions
this.componentInstance = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
this.isRootInsert = true
this.isComment = false
this.isCloned = false
this.isOnce = false
this.asyncFactory = asyncFactory
this.asyncMeta = undefined
this.isAsyncPlaceholder = false
}
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
get child (): Component | void {
return this.componentInstance
}
}
vnode其实就是虚拟节点的简称,通过js模拟真实的DOM节点,我们通过render函数生成虚拟节点的目的,就是为了减少DOM操作,而以js的计算来替代DOM操作,js计算完成后,最后一步再将虚拟节点转换成真实DOM挂载到真正的页面上。
到此为止,我们已经清楚了Vue._render()的目的了,就是生成一个虚拟节点vnode并返回。下一步,就应该执行Vue._update(vnode, hydrating)(hydrating与服务端渲染相关,不用关注,在浏览器端为false)了,
下一节我们继续分析: