Vue虛擬dom被創(chuàng)建的方法
先來看生成虛擬dom的入口文件:
...
import { parse } from './parser/index'
import { optimize } from './optimizer'
import { generate } from './codegen/index'
...
const ast = parse(template.trim(), options)
if (options.optimize !== false) {
optimize(ast, options)
}
const code = generate(ast, options)
...我們看到了AST經(jīng)過三輪加工,最終脫胎換骨成為render function code。那么我們這一章就來講AST的第三次試煉。入口文件./codegen/index
export function generate (
ast: ASTElement | void,
options: CompilerOptions
): CodegenResult {
const state = new CodegenState(options)
const code = ast ? genElement(ast, state) : '_c("div")'
return {
render: `with(this){return $[code]}`,
staticRenderFns: state.staticRenderFns
}
}
我們來看generate函數(shù)內(nèi)部構(gòu)造,返回render是一個with(this){return $[code]}包起來的一串東西,staticRenderFns是在編譯過程中會把那些不會變的靜態(tài)節(jié)點(diǎn)打上標(biāo)記,設(shè)置為true,然后在渲染階段單獨(dú)渲染。
那么genElement函數(shù)的作用是什么呢?
export function genElement (el: ASTElement, state: CodegenState): string {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el, state)
} else if (el.once && !el.onceProcessed) {
return genOnce(el, state)
} else if (el.for && !el.forProcessed) {
return genFor(el, state)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el, state) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el, state)
} else {
// component or element
let code
if (el.component) {
code = genComponent(el.component, el, state)
} else {
const data = el.plain ? undefined : genData(el, state)
const children = el.inlineTemplate ? null : genChildren(el, state, true)
code = `_c('${el.tag}'${ data ? `,${data}` : '' // data }${ children ? `,${children}` : '' // children })`
}
// module transforms
for (let i = 0; i < state.transforms.length; i++) {
code = state.transforms[i](el, code)
}
return code
}
}我們可以看到有無限個if else在嵌套,而且once、for、if、tag就是Vue本身的屠特殊標(biāo)簽,并且最后有return code 那么就是拼接字符串。
那么我們來看一看生成的with(this){return $[code]}長啥樣:
<div id="app">
<ul>
<li v-for="item in items">
itemid:{{item.id}}
</li>
</ul>
</div>
經(jīng)過compile之后轉(zhuǎn)化成:
with(this){
return
_c('div',{
attrs:{"id":"app"}
},
[_c('ul',_l((items),function(item){
return _c('li',
[_v("\n itemid:"+_s(item.id)+"\n ")]
)}
)
)]
)}
到這里我們就把tamplate三次錘煉講完了,那么render function code 有了,那真正的渲染函數(shù)在哪呢?進(jìn)一步來揭曉:
return {
ast, //AST模型
render: code.render, //render函數(shù)字符串
staticRenderFns: code.staticRenderFns //靜態(tài)節(jié)點(diǎn)render函數(shù)字符串
}
我們暴露出去一個ast、render、staticRenderFns分別為AST模型,render函數(shù)字符串,靜態(tài)的render函數(shù)字符串,那么我們的render函數(shù)在那里呢?
我們知道在Vue初始化的時(shí)候initRender:
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)
該方法向vue上掛載了兩個方法,一個服務(wù)于用戶手寫的render函數(shù),一個則用于template模板。
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 {
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
}
}
向vue原型上掛載了_render方法,該方法在mount的過程中會被調(diào)用生成一個vnode實(shí)例用于update對比生成一個新的dom對象并對原dom節(jié)點(diǎn)進(jìn)行替換,該方法將會拿到option上定義render方法:
- 用戶自定義的
render tamplate用戶自定義的是這樣的- 參考vue實(shí)戰(zhàn)視頻講解:進(jìn)入學(xué)習(xí)
new Vue({
el:"#app",
render(createElement){
return createElement("div",{
attr:{
id:"app"
}
},this.message)
},
data(){
return {
message:"hello"
}
}
})一種則是使用的template方式,但是該方法最終在mount的過程中通過調(diào)用compileToFunctions會被轉(zhuǎn)化render函數(shù),也就是說,最終供_render方法使用的實(shí)際上就是我們自定義的render函數(shù),在初始化render中會代理Vue實(shí)例vm._renderProxy,其實(shí)就是vue,那么vm.$createElement就是添加在Vue原型上的一個方法(initRender階段),所以就是createElement方法
/** * 創(chuàng)建vnode節(jié)點(diǎn), 本質(zhì)上是調(diào)_createElement方法, 這里做一層封裝, 來兼容更多情況 */
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
}
// 根據(jù)normalizationType的不同, 后續(xù)處理children的方式也不同, 詳見core/vdom/helpers/normalzie-children.js
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> {
// 如果節(jié)點(diǎn)的data已經(jīng)是響應(yīng)式, 即已有__ob__屬性, 直接返回空節(jié)點(diǎn)并發(fā)出警告
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()
}
// 處理動態(tài)組件
// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
tag = data.is
}
// 沒有tag字段的組件直接返回一個空節(jié)點(diǎn)
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// warn against non-primitive key
// 檢查key是否是string or number
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
// 對于children數(shù)組的兩種處理方式, 詳見helper/normalize-children.js
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
/** * 先對tag進(jìn)行判斷 如果是 string ,接著判斷是否是dom內(nèi)置的節(jié)點(diǎn),如果是則直接創(chuàng)建一個普通 VNode * 如果是為已注冊的組件名,則通過 createComponent 創(chuàng)建一個組件類型的 VNode * 否則創(chuàng)建一個未知的標(biāo)簽的 VNode * * 如果tag是Component類型, 通過createComponent創(chuàng)建一個節(jié)點(diǎn) */
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)
}
// 對vnode進(jìn)行標(biāo)準(zhǔn)化處理, 保證每次都返回一個標(biāo)準(zhǔn)格式的vnode
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()
}
}
// 對每個children節(jié)點(diǎn)應(yīng)用命名空間
function applyNS (vnode, ns, force) {
vnode.ns = ns
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
ns = undefined
force = true
}
if (isDef(vnode.children)) {
for (let i = 0, l = vnode.children.length; i < l; i++) {
const child = vnode.children[i]
if (isDef(child.tag) && (
isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
applyNS(child, ns, force)
}
}
}
}
// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
// 對于style和class進(jìn)行深度遞歸綁定
function registerDeepBindings (data) {
if (isObject(data.style)) {
traverse(data.style)
}
if (isObject(data.class)) {
traverse(data.class)
}
}
其中在判斷ALWAYS_NORMALIZE與normalizationType時(shí)候,用戶手寫的ALWAYS_NORMALIZE一直是true,所以就會調(diào)用normalizeChildren(children)
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
}
export function normalizeChildren (children: any): ?Array<VNode> {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
- 當(dāng)
childre是子組件的時(shí)候就會扁平化 - 當(dāng)
children是基礎(chǔ)數(shù)據(jù)類型的時(shí)候,直接調(diào)用createTextNode函數(shù)變成文本節(jié)點(diǎn) - 當(dāng)
children是數(shù)組的時(shí)候,會調(diào)用normalizeArrayChildren進(jìn)行格式化
最后調(diào)用vnode = new VNode()生成一個vnode。
這一章講解了generate解析AST對象生成render function code在到虛擬VNode是怎么生成出來的,下一章講一個核心概念diff算法
到此這篇關(guān)于Vue虛擬dom是如何被創(chuàng)建的的文章就介紹到這了,更多相關(guān)Vue虛擬dom內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue項(xiàng)目實(shí)現(xiàn)點(diǎn)擊目標(biāo)區(qū)域之外可關(guān)閉(隱藏)目標(biāo)區(qū)域
這篇文章主要介紹了vue項(xiàng)目實(shí)現(xiàn)點(diǎn)擊目標(biāo)區(qū)域之外可關(guān)閉(隱藏)目標(biāo)區(qū)域,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
vant-ui框架的一個bug(解決切換后onload不觸發(fā))
這篇文章主要介紹了vant-ui框架的一個bug(解決切換后onload不觸發(fā)),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
使用Vue.js創(chuàng)建一個時(shí)間跟蹤的單頁應(yīng)用
這篇文章主要介紹了使用Vue.js創(chuàng)建一個時(shí)間跟蹤的單頁應(yīng)用的相關(guān)資料,非常不錯,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11
Django+Vue.js實(shí)現(xiàn)搜索功能
本文主要介紹了Django+Vue.js實(shí)現(xiàn)搜索功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06
ant?design?vue?pro?支持多頁簽?zāi)J絾栴}
這篇文章主要介紹了ant?design?vue?pro?支持多頁簽?zāi)J絾栴},具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
vue如何實(shí)現(xiàn)對請求參數(shù)進(jìn)行簽名
這篇文章主要介紹了vue如何實(shí)現(xiàn)對請求參數(shù)進(jìn)行簽名問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

