由於對Vue.js很感興趣,並且平時工做的技術棧也是Vue.js,這幾個月花了些時間研究學習了一下Vue.js源碼,並作了總結與輸出。
文章的原地址:github.com/answershuto…。
在學習過程當中,爲Vue加上了中文的註釋github.com/answershuto…,但願能夠對其餘想學習Vue源碼的小夥伴有所幫助。
可能會有理解存在誤差的地方,歡迎提issue指出,共同窗習,共同進步。javascript
在刀耕火種的年代,咱們須要在各個事件方法中直接操做Dom來達到修改視圖的目的。可是當應用一大就會變得難以維護。html
那咱們是否是能夠把真實Dom樹抽象成一棵以javascript對象構成的抽象樹,在修改抽象樹數據後將抽象樹轉化成真實Dom重繪到頁面上呢?因而虛擬Dom出現了,它是真實Dom的一層抽象,用屬性描述真實Dom的各個特性。當它發生變化的時候,就會去修改視圖。vue
可是這樣的javascript操做Dom進行重繪整個視圖層是至關消耗性能的,咱們是否是能夠每次只更新它的修改呢?因此Vue.js將Dom抽象成一個以javascript對象爲節點的虛擬Dom樹,以VNode節點模擬真實Dom,能夠對這顆抽象樹進行建立節點、刪除節點以及修改節點等操做,在這過程當中都不須要操做真實Dom,只須要操做javascript對象,大大提高了性能。修改之後通過diff算法得出一些須要修改的最小單位,再將這些小單位的視圖進行更新。這樣作減小了不少不須要的Dom操做,大大提升了性能。java
Vue就使用了這樣的抽象節點VNode,它是對真實Dom的一層抽象,而不依賴某個平臺,它能夠是瀏覽器平臺,也能夠是weex,甚至是node平臺也能夠對這樣一棵抽象Dom樹進行建立刪除修改等操做,這也爲先後端同構提供了可能。node
先來看一下Vue.js源碼中對VNode類的定義。git
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
functionalContext: Component | void; // only for functional component root nodes
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
componentInstance: Component | void; // component instance
parent: VNode | void; // component placeholder node
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?
constructor (
tag?: string,
data?: VNodeData,
children?: ?Array<VNode>,
text?: string,
elm?: Node,
context?: Component,
componentOptions?: VNodeComponentOptions
) {
/*當前節點的標籤名*/
this.tag = tag
/*當前節點對應的對象,包含了具體的一些數據信息,是一個VNodeData類型,能夠參考VNodeData類型中的數據信息*/
this.data = data
/*當前節點的子節點,是一個數組*/
this.children = children
/*當前節點的文本*/
this.text = text
/*當前虛擬節點對應的真實dom節點*/
this.elm = elm
/*當前節點的名字空間*/
this.ns = undefined
/*編譯做用域*/
this.context = context
/*函數化組件做用域*/
this.functionalContext = undefined
/*節點的key屬性,被看成節點的標誌,用以優化*/
this.key = data && data.key
/*組件的option選項*/
this.componentOptions = componentOptions
/*當前節點對應的組件的實例*/
this.componentInstance = undefined
/*當前節點的父節點*/
this.parent = undefined
/*簡而言之就是是否爲原生HTML或只是普通文本,innerHTML的時候爲true,textContent的時候爲false*/
this.raw = false
/*靜態節點標誌*/
this.isStatic = false
/*是否做爲跟節點插入*/
this.isRootInsert = true
/*是否爲註釋節點*/
this.isComment = false
/*是否爲克隆節點*/
this.isCloned = false
/*是否有v-once指令*/
this.isOnce = false
}
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next https://github.com/answershuto/learnVue*/
get child (): Component | void {
return this.componentInstance
}
}複製代碼
這是一個最基礎的VNode節點,做爲其餘派生VNode類的基類,裏面定義了下面這些數據。github
tag: 當前節點的標籤名算法
data: 當前節點對應的對象,包含了具體的一些數據信息,是一個VNodeData類型,能夠參考VNodeData類型中的數據信息json
children: 當前節點的子節點,是一個數組後端
text: 當前節點的文本
elm: 當前虛擬節點對應的真實dom節點
ns: 當前節點的名字空間
context: 當前節點的編譯做用域
functionalContext: 函數化組件做用域
key: 節點的key屬性,被看成節點的標誌,用以優化
componentOptions: 組件的option選項
componentInstance: 當前節點對應的組件的實例
parent: 當前節點的父節點
raw: 簡而言之就是是否爲原生HTML或只是普通文本,innerHTML的時候爲true,textContent的時候爲false
isStatic: 是否爲靜態節點
isRootInsert: 是否做爲跟節點插入
isComment: 是否爲註釋節點
isCloned: 是否爲克隆節點
isOnce: 是否有v-once指令
打個比方,好比說我如今有這麼一個VNode樹
{
tag: 'div'
data: {
class: 'test'
},
children: [
{
tag: 'span',
data: {
class: 'demo'
}
text: 'hello,VNode'
}
]
}複製代碼
渲染以後的結果就是這樣的
<div class="test">
<span class="demo">hello,VNode</span>
</div>複製代碼
下面這些方法都是一些經常使用的構造VNode的方法。
/*建立一個空VNode節點*/
export const createEmptyVNode = () => {
const node = new VNode()
node.text = ''
node.isComment = true
return node
}複製代碼
/*建立一個文本節點*/
export function createTextVNode (val: string | number) {
return new VNode(undefined, undefined, undefined, String(val))
}複製代碼
// plain options object: turn it into a constructor https://github.com/answershuto/learnVue
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor)
}
// if at this stage it's not a constructor or an async component factory,
// reject.
/*Github:https://github.com/answershuto*/
/*若是在該階段Ctor依然不是一個構造函數或者是一個異步組件工廠則直接返回*/
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(`Invalid Component definition: ${String(Ctor)}`, context)
}
return
}
// async component
/*處理異步組件*/
if (isUndef(Ctor.cid)) {
Ctor = resolveAsyncComponent(Ctor, baseCtor, context)
if (Ctor === undefined) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
/*若是這是一個異步組件則會不會返回任何東西(undifiened),直接return掉,等待回調函數去觸發父組件更新。s*/
return
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor)
data = data || {}
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data)
}
// extract props
const propsData = extractPropsFromVNodeData(data, Ctor, tag)
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
const listeners = data.on
// replace with listeners with .native modifier
data.on = data.nativeOn
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners
data = {}
}
// merge component management hooks onto the placeholder node
mergeHooks(data)
// return a placeholder vnode
const name = Ctor.options.name || tag
const vnode = new VNode(
`vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
data, undefined, undefined, undefined, context,
{ Ctor, propsData, listeners, tag, children }
)
return vnode
}複製代碼
export function cloneVNode (vnode: VNode): VNode {
const cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions
)
cloned.ns = vnode.ns
cloned.isStatic = vnode.isStatic
cloned.key = vnode.key
cloned.isCloned = true
return cloned
}複製代碼
// 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 {
/*兼容不傳data的狀況*/
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children
children = data
data = undefined
}
/*若是alwaysNormalize爲true,則normalizationType標記爲ALWAYS_NORMALIZE*/
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE
}
/*Github:https://github.com/answershuto*/
/*建立虛擬節點*/
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 {
/* 若是data未定義(undefined或者null)或者是data的__ob__已經定義(表明已經被observed,上面綁定了Oberver對象), https://cn.vuejs.org/v2/guide/render-function.html#約束 那麼建立一個空節點 */
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()
}
/*若是tag不存在也是建立一個空節點*/
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// 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
/*獲取tag的名字空間*/
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
/*從vm實例的option的components中尋找該tag,存在則就是一個組件,建立相應節點,Ctor爲組件的構造類*/
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
/*tag不是字符串的時候則是組件的構造類*/
vnode = createComponent(tag, data, context, children)
}
if (isDef(vnode)) {
/*若是有名字空間,則遞歸全部子節點應用該名字空間*/
if (ns) applyNS(vnode, ns)
return vnode
} else {
/*若是vnode沒有成功建立則建立空節點*/
return createEmptyVNode()
}
}複製代碼
createElement用來建立一個虛擬節點。當data上已經綁定ob的時候,表明該對象已經被Oberver過了,因此建立一個空節點。tag不存在的時候一樣建立一個空節點。當tag不是一個String類型的時候表明tag是一個組件的構造類,直接用new VNode建立。當tag是String類型的時候,若是是保留標籤,則用new VNode建立一個VNode實例,若是在vm的option的components找獲得該tag,表明這是一個組件,不然統一用new VNode建立。
做者:染陌
Email:answershuto@gmail.com or answershuto@126.com
Github: github.com/answershuto
osChina:my.oschina.net/u/3161824/b…
轉載請註明出處。
歡迎關注個人公衆號