八、資料驅動和初始化
前端框架解決的根本問題就是資料和ui同步的問題,vue很好的額解決了那個問題。也就是Vue.js 一個核心思想是資料驅動。所謂資料驅動,是指檢視是由資料驅動生成的,我們對檢視的修改,不會直接操作 DOM,而是通過修改資料。通過分析來弄清楚模板和資料如何渲染成最終的 DOM。
new Vue 發生了什麼
從入口程式碼開始分析,我們先來分析 new Vue 背後發生了哪些事情。我們都知道,new 關鍵字在 Javascript 語言中代表例項化是一個物件,而 Vue 實際上是一個類,類在 Javascript 中是用 Function 來實現的,來看一下原始碼,在src/core/instance/index.js 中。
// 從五個檔案匯入五個方法(不包括 warn) import { initMixin } from './init' import { stateMixin } from './state' import { renderMixin } from './render' import { eventsMixin } from './events' import { lifecycleMixin } from './lifecycle' import { warn } from '../util/index' // 定義 Vue 建構函式 function Vue (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options) } // 將 Vue 作為引數傳遞給匯入的五個方法 initMixin(Vue) stateMixin(Vue) eventsMixin(Vue) lifecycleMixin(Vue) renderMixin(Vue) // 匯出 Vue export default Vue
initMixin
開啟 ./init.js 檔案,找到 initMixin 方法,如下:
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
// ... _init 方法的函式體,此處省略
}
}
這個方法的作用就是在 Vue 的原型上添加了 _init 方法,這個 _init 方法看上去應該是內部初始化的一個方法。在vue內部呼叫
在 Vue 的建構函式裡有這麼一句:this._init(options),這說明,當我們執行 new Vue() 的時候,this._init(options) 將被執行
stateMixin
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData: Object) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
propsDef.set = function () {
warn(`$props is readonly.`, this)
}
}
Object.defineProperty(Vue.prototype, '$data', dataDef)
Object.defineProperty(Vue.prototype, '$props', propsDef)
使用 Object.defineProperty 在 Vue.prototype 上定義了兩個屬性,就是大家熟悉的:$data 和 $props,這兩個屬性的定義分別寫在了 dataDef 以及 propsDef 這兩個物件裡,我們來仔細看一下這兩個物件的定義,首先是 get :
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
可以看到,$data 屬性實際上代理的是 _data 這個例項屬性,而 $props 代理的是 _props 這個例項屬性。然後有一個是否為生產環境的判斷,如果不是生產環境的話,就為 $data 和 $props 這兩個屬性設定一下 set,實際上就是提示你一下:別他孃的想修改我,老子無敵。
也就是說,$data 和 $props 是兩個只讀的屬性,所以,現在讓你使用 js 實現一個只讀的屬性,你應該知道要怎麼做了。
接下來 stateMixin 又在 Vue.prototype 上定義了三個方法:
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
// ...
}
eventsMixin
這個方法在 ./events.js 檔案中,開啟這個檔案找到 eventsMixin 方法,這個方法在 Vue.prototype 上添加了四個方法,分別是:
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {}
Vue.prototype.$once = function (event: string, fn: Function): Component {}
Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {}
Vue.prototype.$emit = function (event: string): Component {}
lifecycleMixin
開啟 ./lifecycle.js 檔案找到相應方法,這個方法在 Vue.prototype 上添加了三個方法:
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {}
Vue.prototype.$forceUpdate = function () {}
Vue.prototype.$destroy = function () {}
renderMixin
它在 render.js 檔案中,這個方法的一開始以 Vue.prototype 為引數呼叫了 installRenderHelpers 函式,這個函式來自於與 render.js 檔案相同目錄下的 render-helpers/index.js 檔案,開啟這個檔案找到 installRenderHelpers 函式:
export function installRenderHelpers (target: any) {
target._o = markOnce
target._n = toNumber
target._s = toString
target._l = renderList
target._t = renderSlot
target._q = looseEqual
target._i = looseIndexOf
target._m = renderStatic
target._f = resolveFilter
target._k = checkKeyCodes
target._b = bindObjectProps
target._v = createTextVNode
target._e = createEmptyVNode
target._u = resolveScopedSlots
target._g = bindObjectListeners
}
renderMixin 方法在執行完 installRenderHelpers 函式之後,又在 Vue.prototype 上添加了兩個方法,分別是:$nextTick 和 _render,最終經過 renderMixin 之後,Vue.prototype 又被添加了如下方法:
Vue.prototype.$nextTick = function (fn: Function) {}
Vue.prototype._render = function (): VNode {}
大概瞭解了每個 *Mixin 方法的作用其實就是包裝 Vue.prototype,在其上掛載一些屬性和方法:
// initMixin(Vue) src/core/instance/init.js **************************************************
Vue.prototype._init = function (options?: Object) {}
// stateMixin(Vue) src/core/instance/state.js **************************************************
Vue.prototype.$data
Vue.prototype.$props
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {}
// eventsMixin(Vue) src/core/instance/events.js **************************************************
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {}
Vue.prototype.$once = function (event: string, fn: Function): Component {}
Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {}
Vue.prototype.$emit = function (event: string): Component {}
// lifecycleMixin(Vue) src/core/instance/lifecycle.js **************************************************
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {}
Vue.prototype.$forceUpdate = function () {}
Vue.prototype.$destroy = function () {}
// renderMixin(Vue) src/core/instance/render.js **************************************************
// installRenderHelpers 函式中
Vue.prototype._o = markOnce
Vue.prototype._n = toNumber
Vue.prototype._s = toString
Vue.prototype._l = renderList
Vue.prototype._t = renderSlot
Vue.prototype._q = looseEqual
Vue.prototype._i = looseIndexOf
Vue.prototype._m = renderStatic
Vue.prototype._f = resolveFilter
Vue.prototype._k = checkKeyCodes
Vue.prototype._b = bindObjectProps
Vue.prototype._v = createTextVNode
Vue.prototype._e = createEmptyVNode
Vue.prototype._u = resolveScopedSlots
Vue.prototype._g = bindObjectListeners
Vue.prototype.$nextTick = function (fn: Function) {}
Vue.prototype._render = function (): VNode {}
// core/index.js 檔案中
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
})
Object.defineProperty(Vue.prototype, '$ssrContext', {
get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
})
// 在 runtime/index.js 檔案中
Vue.prototype.__patch__ = inBrowser ? patch : noop
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
// 在入口檔案 entry-runtime-with-compiler.js 中重寫了 Vue.prototype.$mount 方法
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// ... 函式體
}
Vue 建構函式的靜態屬性和方法(全域性API)
core/index.js 檔案
// 從 Vue 的出生檔案匯入 Vue
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'
// 將 Vue 建構函式作為引數,傳遞給 initGlobalAPI 方法,該方法來自 ./global-api/index.js 檔案
initGlobalAPI(Vue)
// 在 Vue.prototype 上新增 $isServer 屬性,該屬性代理了來自 core/util/env.js 檔案的 isServerRendering 方法
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
})
// 在 Vue.prototype 上新增 $ssrContext 屬性
Object.defineProperty(Vue.prototype, '$ssrContext', {
get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
})
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
})
// Vue.version 儲存了當前 Vue 的版本號
Vue.version = '__VERSION__'
// 匯出 Vue
export default Vue
檔案匯入了三個變數
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'
其中 initGlobalAPI 是一個函式,並且以 Vue 建構函式作為引數進行呼叫:
initGlobalAPI(Vue)
然後在 Vue.prototype 上分別添加了兩個只讀的屬性,分別是:$isServer 和 $ssrContext。接著又在 Vue 建構函式上定義了 FunctionalRenderContext 靜態屬性,並且 FunctionalRenderContext 屬性的值為來自 core/vdom/create-functional-component.js 檔案的 FunctionalRenderContext,之所以在 Vue 建構函式上暴露該屬性,是為了在 ssr 中使用它。
這看上去像是在 Vue 上新增一些全域性的API,實際上就是這樣的,這些全域性API以靜態屬性和方法的形式被新增到 Vue 建構函式上,開啟 src/core/global-api/index.js 檔案找到 initGlobalAPI 方法
// config
const configDef = {}
configDef.get = () => config
if (process.env.NODE_ENV !== 'production') {
configDef.set = () => {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
)
}
}
Object.defineProperty(Vue, 'config', configDef)
這段程式碼的作用是在 Vue 建構函式上新增 config 屬性,這個屬性的新增方式類似我們前面看過的 $data 以及 $props,也是一個只讀的屬性,並且當你試圖設定其值時,在非生產環境下會給你一個友好的提示。
那 Vue.config 的值是什麼呢?在 src/core/global-api/index.js 檔案的開頭有這樣一句:
import config from '../config'
所以 Vue.config 代理的是從 core/config.js 檔案匯出的物件。
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive
}
在 Vue 上添加了 util 屬性,這是一個物件,這個物件擁有四個屬性分別是:warn、extend、mergeOptions 以及 defineReactive。這四個屬性來自於 core/util/index.js 檔案。
這裡有一段註釋,大概意思是 Vue.util 以及 util 下的四個方法都不被認為是公共API的一部分,要避免依賴他們,但是你依然可以使用,只不過風險你要自己控制。並且,在官方文件上也並沒有介紹這個全域性API,所以能不用盡量不要用。
然後是這樣一段程式碼:
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
Vue.options = Object.create(null)
這段程式碼比較簡單,在 Vue 上添加了四個屬性分別是 set、delete、nextTick 以及 options,這裡要注意的是 Vue.options,現在它還只是一個空的物件,通過 Object.create(null) 建立。
不過接下來,Vue.options 就不是一個空的物件了,因為下面這段程式碼:
ASSET_TYPES.forEach(type => {
Vue.options[type + 's'] = Object.create(null)
})
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue
extend(Vue.options.components, builtInComponents)
上面的程式碼中,ASSET_TYPES 來自於 shared/constants.js 檔案,開啟這個檔案,發現 ASSET_TYPES 是一個數組:
export const ASSET_TYPES = [
'component',
'directive',
'filter'
]
所以當下面這段程式碼執行完後:
ASSET_TYPES.forEach(type => {
Vue.options[type + 's'] = Object.create(null)
})
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue
Vue.options 將變成這樣:
Vue.options = {
components: Object.create(null),
directives: Object.create(null),
filters: Object.create(null),
_base: Vue
}
緊接著,是這句程式碼:
extend(Vue.options.components, builtInComponents)
總之這句程式碼的意思就是將 builtInComponents 的屬性混合到 Vue.options.components 中,其中 builtInComponents 來自於 core/components/index.js 檔案,該檔案如下:
import KeepAlive from './keep-alive'
export default {
KeepAlive
}
所以最終 Vue.options.components 的值如下
Vue.options.components = {
KeepAlive
}
那麼到現在為止,Vue.options 已經變成了這樣:
Vue.options = {
components: {
KeepAlive
},
directives: Object.create(null),
filters: Object.create(null),
_base: Vue
}
我們繼續看程式碼,在 initGlobalAPI 方法的最後部分,以 Vue 為引數呼叫了四個 init* 方法
initUse(Vue) // 新增全域性api use
initMixin(Vue) // 新增全域性api mixin
initExtend(Vue) // initExtend 方法在 Vue 上添加了 Vue.cid 靜態屬性,和 Vue.extend 靜態方法
initAssetRegisters(Vue) // 添加了Vue.component Vue.directive Vue.filter
全域性api
// initGlobalAPI
Vue.config
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive
}
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
Vue.options = {
components: {
KeepAlive
// Transition 和 TransitionGroup 元件在 runtime/index.js 檔案中被新增
// Transition,
// TransitionGroup
},
directives: Object.create(null),
// 在 runtime/index.js 檔案中,為 directives 添加了兩個平臺化的指令 model 和 show
// directives:{
// model,
// show
// },
filters: Object.create(null),
_base: Vue
}
// initUse ***************** global-api/use.js
Vue.use = function (plugin: Function | Object) {}
// initMixin ***************** global-api/mixin.js
Vue.mixin = function (mixin: Object) {}
// initExtend ***************** global-api/extend.js
Vue.cid = 0
Vue.extend = function (extendOptions: Object): Function {}
// initAssetRegisters ***************** global-api/assets.js
Vue.component =
Vue.directive =
Vue.filter = function (
id: string,
definition: Function | Object
): Function | Object | void {}
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
})
Vue.version = '__VERSION__'
// entry-runtime-with-compiler.js
Vue.compile = compileToFunctions
Vue 平臺化的包裝
core 目錄存放的是與平臺無關的程式碼,所以無論是 core/instance/index.js 檔案還是 core/index.js 檔案,它們都在包裝核心的 Vue,且這些包裝是與平臺無關的。但是,Vue 是一個 Multi-platform 的專案(web和weex),不同平臺可能會內建不同的元件、指令,或者一些平臺特有的功能等等,那麼這就需要對 Vue 根據不同的平臺進行平臺化地包裝,這就是接下來我們要看的檔案,這個檔案也出現在我們尋找 Vue 建構函式的路線上,它就是:platforms/web/runtime/index.js 檔案。
大家可以先開啟 platforms 目錄,可以發現有兩個子目錄 web 和 weex。這兩個子目錄的作用就是分別為相應的平臺對核心的 Vue 進行包裝的。而我們所要研究的 web 平臺,就在 web 這個目錄裡。
platforms/web/runtime/index.js
在 import 語句下面是這樣一段程式碼:
// install platform specific utils
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement
其實這就是在覆蓋預設匯出的 config 物件的屬性,註釋已經寫得很清楚了,安裝平臺特定的工具方法,至於這些東西的作用這裡我們暫且不說,你只要知道它在幹嘛即可。
接著是這兩句程式碼:
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
安裝特定平臺執行時的指令和元件,大家還記得 Vue.options 長什麼樣嗎?在執行這兩句程式碼之前,它長成這樣:
Vue.options = {
components: {
KeepAlive
},
directives: Object.create(null),
filters: Object.create(null),
_base: Vue
}
經過:
extend(Vue.options.components, platformComponents)
Vue.options = {
components: {
KeepAlive,
Transition,
TransitionGroup
},
directives: {
model,
show
},
filters: Object.create(null),
_base: Vue
}
這樣,這兩句程式碼的目的我們就搞清楚了,其作用是在 Vue.options 上新增 web 平臺執行時的特定元件和指令。
接下來是這段:
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
首先在 Vue.prototype 上新增 patch 方法,如果在瀏覽器環境執行的話,這個方法的值為 patch 函式,否則是一個空函式 noop。然後又在 Vue.prototype 上添加了 $mount 方法,我們暫且不關心 $mount 方法的內容和作用。
再往下的一段程式碼是 vue-devtools 的全域性鉤子,它被包裹在 setTimeout 中,最後匯出了 Vue。
現在我們就看完了 platforms/web/runtime/index.js 檔案,該檔案的作用是對 Vue 進行平臺化地包裝:
- 設定平臺化的 Vue.config。
- 在 Vue.options 上混合了兩個指令(directives),分別是 model 和 show。
- 在 Vue.options 上混合了兩個元件(components),分別是 Transition 和 TransitionGroup。
- 在 Vue.prototype 上添加了兩個方法:patch 和 $mount。
在經過這個檔案之後,Vue.options 以及 Vue.config 和 Vue.prototype 都有所變化,我們把這些變化更新到對應的 附錄 檔案裡,都可以檢視的到
with compiler
在看完 runtime/index.js 檔案之後,其實 執行時 版本的 Vue 建構函式就已經“成型了”。我們可以開啟 entry-runtime.js 這個入口檔案,這個檔案只有兩行程式碼:
import Vue from './runtime/index'
export default Vue
可以發現,執行時 版的入口檔案,匯出的 Vue 就到 ./runtime/index.js 檔案為止。然而我們所選擇的並不僅僅是執行時版,而是完整版的 Vue,入口檔案是 entry-runtime-with-compiler.js,我們知道完整版和執行時版的區別就在於 compiler,所以其實在我們看這個檔案的程式碼之前也能夠知道這個檔案的作用:就是在執行時版的基礎上新增 compiler,對沒錯,這個檔案就是幹這個的,接下來我們就看看它是怎麼做的,開啟 entry-runtime-with-compiler.js 檔案:
// ... 其他 import 語句
// 匯入 執行時 的 Vue
import Vue from './runtime/index'
// ... 其他 import 語句
// 從 ./compiler/index.js 檔案匯入 compileToFunctions
import { compileToFunctions } from './compiler/index'
// 根據 id 獲取元素的 innerHTML
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
// 使用 mount 變數快取 Vue.prototype.$mount 方法
const mount = Vue.prototype.$mount
// 重寫 Vue.prototype.$mount 方法
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// ... 函式體省略
}
/**
* 獲取元素的 outerHTML
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
// 在 Vue 上新增一個全域性API `Vue.compile` 其值為上面匯入進來的 compileToFunctions
Vue.compile = compileToFunctions
// 匯出 Vue
export default Vue
上面程式碼是簡化過的,但是保留了所有重要的部分,該檔案的開始是一堆 import 語句,其中重要的兩句 import 語句就是上面程式碼中出現的那兩句,一句是匯入執行時的 Vue,一句是從 ./compiler/index.js 檔案匯入 compileToFunctions,並且在倒數第二句程式碼將其新增到 Vue.compile 上。
然後定義了一個函式 idToTemplate,這個函式的作用是:獲取擁有指定 id 屬性的元素的 innerHTML。
之後快取了執行時版 Vue 的 Vue.prototype.$mount 方法,並且進行了重寫。
接下來又定義了 getOuterHTML 函式,用來獲取一個元素的 outerHTML。
這個檔案執行下來,對 Vue 的影響有兩個,第一個影響是它重寫了 Vue.prototype.$mount 方法;第二個影響是添加了 Vue.compile 全域性API,目前我們只需要獲取這些資訊就足夠了,我們把這些影響同樣更新到 附錄 對應的檔案中,也都可以檢視的到。
資料驅動
在 Vue.js 中我們可以採用簡潔的模板語法來宣告式的將資料渲染為 DOM:
例子
<div id="app">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
這段 js 程式碼很簡單,只是簡單地呼叫了 Vue,傳遞了兩個選項 el 以及 data。這段程式碼的最終效果就是在頁面中渲染為如下 DOM:
<div id="app">Hello Vue!</div>
其中 {{ message }} 被替換成了 Hello Vue!,並且當我們嘗試修改 data.test 的值的時候
vm.$data.message = 2
// 或
vm.message = 2
那麼頁面的 DOM 也會隨之變化為:
<div id="app">2</div>
new Vue 發生了什麼
從入口程式碼開始分析,我們先來分析 new Vue 背後發生了哪些事情。我們都知道,new 關鍵字在 Javascript 語言中代表例項化是一個物件,而 Vue 實際上是一個類,類在 Javascript 中是用 Function 來實現的,來看一下原始碼,在src/core/instance/index.js 中。
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
一目瞭然,當我們使用 new 操作符呼叫 Vue 的時候,第一句執行的程式碼就是 this._init(options) 方法,其中 options 是我們呼叫 Vue 建構函式時透傳過來的,也就是說:
options = {
el: '#app',
data: {
message: 'Hello Vue!'
}
}
可以看到 Vue 只能通過 new 關鍵字初始化,然後會呼叫 this._init 方法, 該方法在 src/core/instance/init.js 中定義。
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to avoid this being observed
vm._isVue = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`vue ${vm._name} init`, startTag, endTag)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
_init 方法的一開始,是這兩句程式碼:
// this 也就是當前這個 Vue 例項
const vm: Component = this
// 添加了一個唯一標示:_uid每次例項化一個 Vue 例項之後,uid 的值都會 ++
vm._uid = uid++
接下來是這樣一段:
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// 中間的程式碼省略...
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`vue ${vm._name} init`, startTag, endTag)
}
Vue 提供了全域性配置 Vue.config.performance,我們通過將其設定為 true,即可開啟效能追蹤,你可以追蹤四個場景的效能:
- 1、元件初始化(component init)
- 2、編譯(compile),將模板(template)編譯成渲染函式
- 3、渲染(render),其實就是渲染函式的效能,或者說渲染函式執行且生成虛擬DOM(vnode)的效能
- 4、打補丁(patch),將虛擬DOM渲染為真實DOM的效能
其中元件初始化的效能追蹤就是我們在 _init 方法中看到的那樣去實現的,其實現的方式就是在初始化的程式碼的開頭和結尾分別使用 mark 函式打上兩個標記,然後通過 measure 函式對這兩個標記點進行效能計算
瞭解了這兩段效能追蹤的程式碼之後,我們再來看看這兩段程式碼中間的程式碼,也就是被追蹤效能的程式碼,如下:
// a flag to avoid this being observed
vm._isVue = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
Vue 初始化主要就幹了幾件事情,合併配置,初始化生命週期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等。
上面的程式碼是那兩段效能追蹤的程式碼之間全部的內容,我們逐一分析,首先在 Vue 例項上新增 _isVue 屬性,並設定其值為 true。目的是用來標識一個物件是 Vue 例項,即如果發現一個物件擁有 _isVue 屬性並且其值為 true,那麼就代表該物件是 Vue 例項。這樣可以避免該物件被響應系統觀測(其實在其他地方也有用到,但是宗旨都是一樣的,這個屬性就是用來告訴你:我不是普通的物件,我是Vue例項)。
再往下是這樣一段程式碼:
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
上面的程式碼必然會走 else 分支,也就是這段程式碼:
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
這段程式碼在 Vue 例項上添加了 $options 屬性,在 Vue 的官方文件中,你能夠檢視到 $options 屬性的作用,這個屬性用於當前 Vue 的初始化,什麼意思呢?大家要注意我們現在的階段處於 _init() 方法中,在 _init() 方法的內部大家可以看到一系列 init* 的方法,比如:
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
而這些方法才是真正起作用的一些初始化方法,大家可以找到這些方法看一看,在這些初始化方法中,無一例外的都使用到了例項的 $options 屬性,即 vm.$options。所以 $options 這個屬性的的確確是用於 Vue 例項初始化的,只不過在初始化之前,我們需要一些手段來產生 $options 屬性,而這就是 mergeOptions 函式的作用,接下來我們就來看看 mergeOptions 都做了些什麼,又有什麼意義。
初始化規範程式碼等,看初始化合並策略,那篇接著闡述資料驅動。
Vue 例項掛載的實現
Vue 中我們是通過 $mount 例項方法去掛載 vm 的,$mount 方法在多個檔案中都有定義,如 src/platform/web/entry-runtime-with-compiler.js、src/platform/web/runtime/index.js、src/platform/weex/runtime/index.js。因為 $mount 這個方法的實現是和平臺、構建方式都相關的。接下來我們重點分析帶 compiler 版本的 $mount 實現,因為拋開 webpack 的 vue-loader,我們在純前端瀏覽器環境分析 Vue 的工作原理,有助於我們對原理理解的深入。
compiler 版本的 $mount 實現非常有意思,先來看一下 src/platform/web/entry-runtime-with-compiler.js 檔案中定義:
// 儲存之前的定義的$mount
const mount = Vue.prototype.$mount
// 重些$mount, 傳入el和hydrating 返回元件
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// 是元素就不獲取,不是獲取
el = el && query(el)
// el 不是是body或者html
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
// 如果沒有定義 render 方法,則會把 el 或者 template 字串轉換成 render 方法
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
如果沒有定義 render 方法,則會把 el 或者 template 字串轉換成 render 方法。這裡我們要牢記,在 Vue 2.0 版本中,所有 Vue 的元件的渲染最終都需要 render 方法,無論我們是用單檔案 .vue 方式開發元件,還是寫了 el 或者 template 屬性,最終都會轉換成 render 方法,那麼這個過程是 Vue 的一個“線上編譯”的過程,它是呼叫 compileToFunctions 方法實現的,編譯過程我們之後會介紹。最後,呼叫原先原型上的 $mount 方法掛載。
原先原型上的 $mount 方法在 src/platform/web/runtime/index.js 中定義,之所以這麼設計完全是為了複用,因為它是可以被 runtime only 版本的 Vue 直接使用的。
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
$mount 方法支援傳入 2 個引數,第一個是 el,它表示掛載的元素,可以是字串,也可以是 DOM 物件,如果是字串在瀏覽器環境下會呼叫 query 方法轉換成 DOM 物件的。第二個引數是和服務端渲染相關,在瀏覽器環境下我們不需要傳第二個引數。
$mount 方法實際上會去呼叫 mountComponent 方法,這個方法定義在 src/core/instance/lifecycle.js 檔案中
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
// 如果是沒有render弄一個空
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
// 執行beforeMount函式
callHook(vm, 'beforeMount')
let updateComponent
// 監控vnode生成的效能
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = () => {
const name = vm._name
const id = vm._uid
const startTag = `vue-perf-start:${id}`
const endTag = `vue-perf-end:${id}`
mark(startTag)
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
mountComponent 核心就是先呼叫 vm._render 方法先生成虛擬 Node,再例項化一個渲染Watcher,在它的回撥函式中會呼叫 updateComponent 方法,最終呼叫 vm._update 更新 DOM。
Watcher 在這裡起到兩個作用,一個是初始化的時候會執行回撥函式,另一個是當 vm 例項中的監測的資料發生變化的時候執行回撥函式,這塊兒我們會在之後的章節中介紹。
函式最後判斷為根節點的時候設定 vm._isMounted 為 true, 表示這個例項已經掛載了,同時執行 mounted 鉤子函式。 這裡注意 vm.$vnode 表示 Vue 例項的父虛擬 Node,所以它為 Null 則表示當前是根 Vue 的例項。
mountComponent 方法的邏輯也是非常清晰的,它會完成整個渲染工作,接下來我們要重點分析其中的細節,也就是最核心的 2 個方法:vm._render 和 vm._update
render
Vue 的 _render 方法是例項的一個私有方法,它用來把例項渲染成一個虛擬 Node。它的定義在 src/core/instance/render.js 檔案中:
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
}
這段程式碼最關鍵的是 render 方法的呼叫,我們在平時的開發工作中手寫 render 方法的場景比較少,而寫的比較多的是 template 模板,在之前的 mounted 方法的實現中,會把 template 編譯成 render 方法,但這個編譯過程是非常複雜的,我們不打算在這裡展開講,之後會專門花一個章節來分析 Vue 的編譯過程。
_render 函式中的 render 方法的呼叫:
vnode = render.call(vm._renderProxy, vm.$createElement)
render 函式中的 createElement 方法就是 vm.$createElement 方法:
export function initRender (vm: Component) {
// ...
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
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)
}
實際上,vm.$createElement 方法定義是在執行 initRender 方法的時候,可以看到除了 vm.$createElement 方法,還有一個 vm._c 方法,它是被模板編譯成的 render 函式使用,而 vm.$createElement 是使用者手寫 render 方法使用的, 這倆個方法支援的引數相同,並且內部都呼叫了 createElement 方法。
vm._render 最終是通過執行 createElement 方法並返回的是 vnode,它是一個虛擬 Node。Vue 2.0 相比 Vue 1.0 最大的升級就是利用了 Virtual DOM。因此在分析 createElement 的實現前,我們先了解一下 Virtual DOM 的概念.
Virtual DOM
真正的 DOM 元素是非常龐大的,因為瀏覽器的標準就把 DOM 設計的非常複雜。當我們頻繁的去做 DOM 更新,會產生一定的效能問題。
而 Virtual DOM 就是用一個原生的 JS 物件去描述一個 DOM 節點,所以它比建立一個 DOM 的代價要小很多。在 Vue.js 中,Virtual DOM 是用 VNode 這麼一個 Class 去描述,它是定義在 src/core/vdom/vnode.js 中的。
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
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
}
}
Virtual DOM 除了它的資料結構的定義,對映到真實的 DOM 實際上要經歷 VNode 的 create、diff、patch 等過程。那麼在 Vue.js 中,VNode 的 create 是通過之前提到的 createElement 方法建立的,我們接下來分析這部分的實現。
snabbdom
virtual dom,虛擬 DOM,用JS模擬Dom結構,Dom變化的對比,放在JS層來做(圖靈完備語言),提高重繪效能
<ul id='list'>
<li class='item'>Item1</li>
<li class='item'>Item2</li>
</ul>
{
tag: 'ul',
attrs: {
id: 'list'
},
children: [
{
tag: 'li',
attrs: { className: 'item' },
children: ['Item1']
}, {
tag: 'li',
attrs: { className: 'item' },
children: ['Item2']
}
]
}
例子
var snabbdom = require('snabbdom');
var patch = snabbdom.init([ // Init patch function with chosen modules
require('snabbdom/modules/class').default, // makes it easy to toggle classes
require('snabbdom/modules/props').default, // for setting properties on DOM elements
require('snabbdom/modules/style').default, // handles styling on elements with support for animations
require('snabbdom/modules/eventlisteners').default, // attaches event listeners
]);
var h = require('snabbdom/h').default; // helper function for creating vnodes
var container = document.getElementById('container');
var vnode = h('div#container.two.classes', {on: {click: someFn}}, [
h('span', {style: {fontWeight: 'bold'}}, 'This is bold'),
' and this is just normal text',
h('a', {props: {href: '/foo'}}, 'I\'ll take you places!')
]);
// Patch into empty DOM element – this modifies the DOM as a side effect
patch(container, vnode);
var newVnode = h('div#container.two.classes', {on: {click: anotherEventHandler}}, [
h('span', {style: {fontWeight: 'normal', fontStyle: 'italic'}}, 'This is now italic type'),
' and this is still just normal text',
h('a', {props: {href: '/bar'}}, 'I\'ll take you places!')
]);
// Second `patch` invocation
patch(vnode, newVnode); // Snabbdom efficiently updates the old view to the new state
h 函式
var vnode = h('ul#list', {}, [
h('li.item', {}, 'Item1'),
h('li.item', {}, 'Item2')
])
{
tag: 'ul',
attrs: {
id: 'list'
},
children: [
{
tag: 'li',
attrs: { className: 'item' },
children: ['Item1']
}, {
tag: 'li',
attrs: { className: 'item' },
children: ['Item2']
}
]
}
patch 函式
patch(container, vnode);
或
patch(vnode, newVnode);
使用vnode來展示例子
var vnode;
function render(data) {
var newVnode = h('table', {}, data.map(function(item){
var tds = []
var i
for (i in item) {
if (item.hasOwnProperty(i)) {
tds.push(h('td', {}, [item[i] + '']))
}
}
}))
return h('tr', {}, tds)
if (vnode) {
path(vnode, newVnode)
} else {
path(container, newVnode)
}
vnode = newVnode
}
- 使用 data 生成 vnode
- 第一次渲染,將 vnode 渲染到 #container 中
- 並將 vnode 快取下來
- 修改 data 之後,用新 data 生成 newVnode
- 將 vnode 和 newVnode 對比
核心 API
- h(‘<標籤名>’, {…屬性…}, […子元素…])
- h(‘<標籤名>’, {…屬性…}, ‘….’)
- patch(container, vnode)
- patch(vnode, newVnode)
diff 演算法
- vdom 中應用 diff 演算法是為了找出需要更新的節點
- vdom 實現過程,createElement 和 updateChildren
- 與核心函式 patch 的關係
具體分析看其他的文章
createElement
Vue.js 利用 createElement 方法建立 VNode,它定義在 src/core/vdom/create-elemenet.js 中:
// 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 | 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)
}
createElement 方法實際上是對 _createElement 方法的封裝,它允許傳入的引數更加靈活,在處理這些引數後,呼叫真正建立 VNode 的函式 _createElement:
_createElement 方法有 5 個引數
- context 表示 VNode 的上下文環境,它是 Component 型別;
- tag 表示標籤,它可以是一個字串,也可以是一個 Component;
- data 表示 VNode 的資料,它是一個 VNodeData 型別,可以在 flow/vnode.js 中找到它的定義,這裡先不展開說;
- children 表示當前 VNode 的子節點,它是任意型別的,它接下來需要被規範為標準的 VNode 陣列;
- normalizationType 表示子節點規範的型別,型別不同規範的方法也就不一樣,它主要是參考 render 函式是編譯生成的還是使用者手寫的。
createElement 函式的流程略微有點多,我們接下來主要分析 2 個重點的流程 —— children 的規範化以及 VNode 的建立。
children 的規範化
由於 Virtual DOM 實際上是一個樹狀結構,每一個 VNode 可能會有若干個子節點,這些子節點應該也是 VNode 的型別。_createElement 接收的第 4 個引數 children 是任意型別的,因此我們需要把它們規範成 VNode 型別。
這裡根據 normalizationType 的不同,呼叫了 normalizeChildren(children) 和 simpleNormalizeChildren(children) 方法,它們的定義都在 src/core/vdom/helpers/normalzie-children.js 中:
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
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
export function normalizeChildren (children: any): ?Array<VNode> {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
simpleNormalizeChildren 方法呼叫場景是 render 函式當函式是編譯生成的。理論上編譯生成的 children 都已經是 VNode 型別的,但這裡有一個例外,就是 functional component 函式式元件返回的是一個數組而不是一個根節點,所以會通過 Array.prototype.concat 方法把整個 children 陣列打平,讓它的深度只有一層。
normalizeChildren 方法的呼叫場景有 2 種,一個場景是 render 函式是使用者手寫的,當 children 只有一個節點的時候,Vue.js 從介面層面允許使用者把 children 寫成基礎型別用來建立單個簡單的文字節點,這種情況會呼叫 createTextVNode 建立一個文字節點的 VNode;另一個場景是當編譯 slot、v-for 的時候會產生巢狀陣列的情況,會呼叫 normalizeArrayChildren 方法,接下來看一下它的實現:
function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
const res = []
let i, c, lastIndex, last
for (i = 0; i < children.length; i++) {
c = children[i]
if (isUndef(c) || typeof c === 'boolean') continue
lastIndex = res.length - 1
last = res[lastIndex]
// nested
if (Array.isArray(c)) {
if (c.length > 0) {
c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`)
// merge adjacent text nodes
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
c.shift()
}
res.push.apply(res, c)
}
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c)
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c))
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text)
} else {
// default key for nested array children (likely generated by v-for)
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = `__vlist${nestedIndex}_${i}__`
}
res.push(c)
}
}
}
return res
}
normalizeArrayChildren 接收 2 個引數,children 表示要規範的子節點,nestedIndex 表示巢狀的索引,因為單個 child 可能是一個數組型別。 normalizeArrayChildren 主要的邏輯就是遍歷 children,獲得單個節點 c,然後對 c 的型別判斷,如果是一個數組型別,則遞迴呼叫 normalizeArrayChildren; 如果是基礎型別,則通過 createTextVNode 方法轉換成 VNode 型別;否則就已經是 VNode 型別了,如果 children 是一個列表並且列表還存在巢狀的情況,則根據 nestedIndex 去更新它的 key。這裡需要注意一點,在遍歷的過程中,對這 3 種情況都做了如下處理:如果存在兩個連續的 text 節點,會把它們合併成一個 text 節點。
經過對 children 的規範化,children 變成了一個型別為 VNode 的 Array
VNode 的建立
回到 createElement 函式,規範化 children 後,接下來會去建立一個 VNode 的例項:
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 (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)
}
這裡先對 tag 做判斷,如果是 string 型別,則接著判斷如果是內建的一些節點,則直接建立一個普通 VNode,如果是為已註冊的元件名,則通過 createComponent 建立一個元件型別的 VNode,否則建立一個未知的標籤的 VNode。 如果是 tag 一個 Component 型別,則直接呼叫 createComponent 建立一個元件型別的 VNode 節點。對於 createComponent 建立元件型別的 VNode 的過程,我們之後會去介紹,本質上它還是返回了一個 VNode。
回到 mountComponent 函式的過程,我們已經知道 vm._render 是如何建立了一個 VNode,接下來就是要把這個 VNode 渲染成一個真實的 DOM 並渲染出來,這個過程是通過 vm._update 完成的,接下來分析一下這個過程。
update
Vue 的 _update 是例項的一個私有方法,它被呼叫的時機有 2 個,一個是首次渲染,一個是資料更新的時候。
首次渲染部分就是把虛擬dom渲染成真實的dom,更新的時候,就是對比diff
_update 方法的作用是把 VNode 渲染成真實的 DOM,它的定義在 src/core/instance/lifecycle.js 中:
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode
const prevActiveInstance = activeInstance
activeInstance = vm
vm._vnode = vnode
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
activeInstance = prevActiveInstance
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}
_update 的核心就是呼叫 vm.patch 方法,這個方法實際上在不同的平臺,比如 web 和 weex 上的定義是不一樣的,因此在 web 平臺中它的定義在 src/platforms/web/runtime/index.js 中:
Vue.prototype.__patch__ = inBrowser ? patch : noop
可以看到,甚至在 web 平臺上,是否是服務端渲染也會對這個方法產生影響。因為在服務端渲染中,沒有真實的瀏覽器 DOM 環境,所以不需要把 VNode 最終轉換成 DOM,因此是一個空函式,而在瀏覽器端渲染中,它指向了 patch 方法,它的定義在 src/platforms/web/runtime/patch.js中:
import * as nodeOps from 'web/runtime/node-ops'
import { createPatchFunction } from 'core/vdom/patch'
import baseModules from 'core/vdom/modules/index'
import platformModules from 'web/runtime/modules/index'
// the directive module should be applied last, after all
// built-in modules have been applied.
const modules = platformModules.concat(baseModules)
export const patch: Function = createPatchFunction({ nodeOps, modules })
該方法的定義是呼叫 createPatchFunction 方法的返回值,這裡傳入了一個物件,包含 nodeOps 引數和 modules 引數。其中,nodeOps 封裝了一系列 DOM 操作的方法,modules 定義了一些模組的鉤子函式的實現,我們這裡先不詳細介紹,來看一下 createPatchFunction 的實現,它定義在 src/core/vdom/patch.js 中:
const hooks = ['create', 'activate', 'update', 'remove', 'destroy']
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
}
// ...
return function patch (oldVnode, vnode, hydrating, removeOnly) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
return
}
let isInitialPatch = false
const insertedVnodeQueue = []
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR)
hydrating = true
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
// replacing existing element
const oldElm = oldVnode.elm
const parentElm = nodeOps.parentNode(oldElm)
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
let ancestor = vnode.parent
const patchable = isPatchable(vnode)
while (ancestor) {
for (let i = 0; i &l