VNode是JavaScript對象。VNode表示Virtual DOM
,用JavaScript
對象來描述真實的DOM
把DOM
標(biāo)簽,屬性,內(nèi)容都變成對象的屬性。就像使用JavaScript
對象對一種動物進(jìn)行說明一樣{name: 'Hello Kitty', age: 1, children: null}
。
通過render
將template
模版描述成VNode
,然后進(jìn)行一系列操作之后形成真實的DOM
進(jìn)行掛載。
VNode
因為是JS
對象,不管Node
還是瀏覽器,都可以統(tǒng)一操作,從而獲得了服務(wù)端渲染、原生渲染、手寫渲染函數(shù)等能力。DOM
,任何頁面的變化,都只使用VNode
進(jìn)行操作對比,只需要在最后一步掛載更新DOM
,不需要頻繁操作DOM
,從而提高頁面性能。在Vue
源碼中,VNode
是通過一個構(gòu)造函數(shù)生成的。
export default class VNode { 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 } }
VNode
構(gòu)造函數(shù)看起來十分簡單,先走一遍VNode
的生成過程。
// 模版 <a class="demo" style="color: red" href="#"> generator VNode </a> // VNode描述 { tag: 'a', data: { calss: 'demo', attrs: { href: '#' }, style: { color: 'red' } }, children: ['generator VNode'] }
這個JS
對象,已經(jīng)囊括了整個模板的所有信息,完全可以根據(jù)這個對象來構(gòu)造真實DOM
。
在初始化完選項,解析完模板之后,就需要掛載DOM
了。此時就需要生成VNode
,才能根據(jù) VNode
生成DOM
然后掛載。創(chuàng)建出來的VNode
需要被存起來,主要存放在三個位置:parent
,_vnode
,$vnode
。