VNode說明&作用
VNode是什麼
VNode是JavaScript對象。VNode表示Virtual DOM
,用JavaScript
對象來描述真實的DOM
把DOM
標籤,屬性,內容都變成對象的屬性。就像使用JavaScript
對象對一種動物進行說明一樣{name: 'Hello Kitty', age: 1, children: null}
。
VNode的作用
通過render
將template
模版描述成VNode
,然後進行一系列操作之後形成真實的DOM
進行掛載。
VNode的優點
- 兼容性強,不受執行環境的影響。
VNode
因爲是JS
對象,不管Node
還是瀏覽器,都可以統一操作,從而獲得了服務端渲染、原生渲染、手寫渲染函數等能力。 - 減少操作
DOM
,任何頁面的變化,都只使用VNode
進行操作對比,只需要在最後一步掛載更新DOM
,不需要頻繁操作DOM
,從而提高頁面性能。
VNode如何生成
在Vue
源碼中,VNode
是通過一個構造函數生成的。
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
構造函數看起來十分簡單,先走一遍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
對象,已經囊括了整個模板的所有信息,完全可以根據這個對象來構造真實DOM
。
VNode存放哪些信息
- data:存儲節點的屬性,綁定的事件等
- elm:真實DOM 節點
- context:渲染這個模板的上下文對象
- isStatic:是否是靜態節點
…
VNode存放
在初始化完選項,解析完模板之後,就需要掛載DOM
了。此時就需要生成VNode
,才能根據 VNode
生成DOM
然後掛載。創建出來的VNode
需要被存起來,主要存放在三個位置:parent
,_vnode
,$vnode
。