前言
我們在上一篇的最后講解了vm._render是生成虛擬dom的關(guān)鍵湿诊,那么我們來看看他是如何生成的,下面是他的源碼
Vue.prototype._render = function (): VNode {
const vm: Component = this
const { render, _parentVnode } = vm.$options
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
)
}
// 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 {
// There's no need to maintain a stack becaues all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = vm
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' && 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
}
} finally {
currentRenderingInstance = null
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0]
}
// 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
}
解釋
- 從vm.$options中獲取編譯好的函數(shù)瘦材,然后進(jìn)行了 vnode = render.call(vm._renderProxy, vm.$createElement)厅须,其中vm._renderProxy就是new Proxy(vm, handler),把vm做了一層代理
- vm.$createElement全局搜索一下就知道是在initRender中定義了vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true),如果創(chuàng)建虛擬dom出錯(cuò)食棕,就看有沒有renderError函數(shù)朗和,做一個(gè)錯(cuò)誤邊界處理错沽,在沒有的話,讓虛擬dom賦值_parentVnode例隆,_parentVnode如果不是虛擬dom甥捺,那么就賦值空節(jié)點(diǎn)的虛擬dom
createElement 做了什么事情
createElement在文件../vdom/create-element里面,下面是他的源碼
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)
}
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
}
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 ((!data || !data.pre) && 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()
}
}
解釋
- createElement首先對傳入的參數(shù)做了一個(gè)重載镀层,如果傳入的data沒有镰禾,后面的參數(shù)就往前移動(dòng)一個(gè)位置,然后調(diào)用_createElement,下面我們看看_createElement做了什么
- 首先判斷data是不是已經(jīng)被監(jiān)聽了唱逢,根據(jù)_ob_去判斷吴侦,如果是的話報(bào)一個(gè)警告,然后如果沒有傳入tag標(biāo)簽,直接返回一個(gè)空的虛擬節(jié)點(diǎn)
- 接著對childern做一個(gè)處理坞古,如果children是一個(gè)簡單的數(shù)組類型备韧,只需要進(jìn)行一層的數(shù)組平拍simpleNormalizeChildren,如果是一個(gè)復(fù)雜的數(shù)組類型則需要進(jìn)行normalizeChildren(),這么做的目的就是遞歸遍歷痪枫,讓節(jié)點(diǎn)和子節(jié)點(diǎn)全部都生成對應(yīng)的虛擬dom
- 如果tag是字符串织堂,就通過new Vnode來創(chuàng)建虛擬dom,如果不是字符串,肯定是組件了奶陈,tag為空的情況最開始已經(jīng)處理了易阳,就執(zhí)行createComponent來創(chuàng)建一個(gè)虛擬dom
- 最后來看看new Vnode的做的事情
new Vnode分析
new Vnode 創(chuàng)建的是一個(gè)虛擬dom,其實(shí)就是一個(gè)裝有很多屬性的對象吃粒,和真實(shí)的dom做一個(gè)映射潦俺,目的是去渲染真實(shí)的dom,那么為什么不直接去渲染dom徐勃,因?yàn)関ue中dom不僅有create的過程事示,還有diff,patch的過程。為了使得diff的過程花費(fèi)的時(shí)間更短僻肖,虛擬dom就出來了肖爵,下面我們來看看new 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
devtoolsMeta: ?Object; // used to store functional render context for devtools
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的源碼很簡單,就是定義一些列屬性的對象檐涝,用來和真實(shí)dom進(jìn)行映射遏匆,從而渲染出真實(shí)的dom,比較重要得屬性比如tag,data,children
到此虛擬dom已經(jīng)完成了谁榜,那么如果根據(jù)虛擬dom生成正常的渲染dom了,那么就得看看vm._update凡纳,下一篇文章再將