Vue源碼探祕(四)(實例掛載$mount)

引言

在上一篇文章的結尾,咱們提到數據渲染到DOM的關鍵就是調用vm.$mount方法來掛載vm。這一步是在_init函數的結尾被調用的:html

// src/core/instance/init.js
Vue.prototype._init = function (options?: Object) {
// ...
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
複製代碼

本篇文章,咱們來分析一下vm.$mount內部具體發生了什麼。vue

實例掛載($mount)

回顧以前的文章,咱們知道$mount被定義在src/platforms/web/runtime/index.js中:node

// 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方法,在src/platform/web/entry-runtime-with-compiler.jssrc/platform/weex/runtime/index.js都有定義。由於$mount方法的實現是和平臺、構建方式都相關的。web

在運行時(Runtime Only)版本的Vue中,調用的就是上面的這個$mount函數。而在完整版(Runtime + Compiler)的Vue中,$mount函數在src/platform/web/entry-runtime-with-compiler.js中被重寫,這部分代碼是咱們這裏要着重分析的。先看一下總體結構:緩存

// src/platforms/web/entry-runtime-with-compiler.js
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component
{
el = el && query(el)

// ...

return mount.call(this, el, hydrating);
}
複製代碼

這裏先拿到了Runtime Only版本的$mount方法,而後進行重寫,最後又調用了Runtime Only版本的$mount方法。參數的類型檢查代表el能夠是字符串或DOM節點。接下來又調用了query方法:weex

// src/platforms/web/util/index.js
/**
* Query an element selector if it's not an element already.
*/

export function query (el: string | Element): Element {
if (typeof el === 'string') {
const selected = document.querySelector(el)
if (!selected) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + el
)
return document.createElement('div')
}
return selected
} else {
return el
}
}
複製代碼

query函數的邏輯比較簡單: 若是el是一個字符串,就調用querySelector獲取節點並返回;若是節點不存在就拋出警告並建立一個div節點。若是el是一個節點就直接返回。app

咱們接着往下分析,先來看第一小段:編輯器

/* 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
}
複製代碼

這裏去檢查el是否是根節點(html)、(body),若是是就拋出警告並中止掛載。ide

Vue是不能掛載在bodyhtml這樣的根節點上的,由於掛載實際上就是把el節點替換爲組件的模版。函數

繼續往下看:

const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
// [1] ...
} else if (el) {
template = getOuterHTML(el)
}
// [2] ...
}
複製代碼

首先判斷render函數是否存在,若是未定義則需作進一步處理。

Vue2.0 開始,全部組件的渲染都須要用到render函數,不管是咱們上一節的例子仍是使用.vue文件編寫。

進入if判斷後先拿到options.template,若是template存在就執行[1]處的代碼:

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
}
複製代碼

先判斷template是不是字符串,若是是字符串並且是id選擇器,經過idToTemplate方法拿到相應節點,若是拿不到會拋出警告。若是是字符串但不是選擇器,不做處理。

若是template是一個節點,那麼獲取它的innerHTML

若是template既不是字符串也不是一個節點,那麼拋出警告並結束掛載。

若是template不存在,接着判斷el是否存在,存在則執行template = getOuterHTML(el)。來看下getOuterHTML函數:

// src/platforms/web/entry-runtime-with-compiler.js
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/

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
}
}
複製代碼

這裏判斷el.outerHTML是否存在,有就返回outerHTML

IE9-11SVG 標籤元素是沒有 innerHTMLouterHTML 這兩個屬性的。

else中就是對以上狀況的兼容處理: 在el的外面包裝了一層div,而後獲取該divinnerHTML

這樣不管是 template 仍是 el ,都被轉爲了字符串模板,而後執行[2]處的代碼:

if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}

const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
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')
}
}
複製代碼

這裏先判斷template是否存在(template可能爲空字符串)。能夠清楚的看到進入if語句內,裏面有兩個相同的if語句,這與咱們以前介紹_init函數時遇到的同樣,都是用於性能追蹤。

中間這段代碼調用了compileToFunctions函數,返回的render函數將其掛載到options.render上。關於compileToFunctions的具體實現,我會在後面的章節中詳細介紹。

最後執行了:

return mount.call(this, el, hydrating)
複製代碼

這裏是調用以前緩存的在src/platforms/web/runtime/index.js中定義的$mount函數:

// src/platforms/web/runtime/index.js

// 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 又把 el 從字符串轉換成了節點而後傳給了 mountComponent 函數。和上面同樣,這裏把 mountComponent 函數的代碼分紅幾部分,先來看第一部分:

// src/core/instance/lifecycle.js

export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component
{
vm.$el = el
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
)
}
}
}
callHook(vm, 'beforeMount')

// ...
}
複製代碼

先將el保存到vm.$el上,而後判斷前面的template是否被正確的轉換成了render函數。若是轉換失敗,將createEmptyVNode做爲render函數。createEmptyVNode函數會建立一個空的VNode對象。這部分會放在後面章節介紹。

在非生產環境下(通常是開發版本下),若是編寫了template或者el的同時又使用了Runtime Only版本的Vue,致使在$mount中不能編譯成render函數,則會拋出警告;另外若是既沒有template也沒有render函數也會拋出警告。

接下來調用的callHook函數是生命週期相關,會在後面的生命週期章節詳細介紹。繼續往下看:

let updateComponent
/* 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)
}
}
複製代碼

if語句裏面是再熟悉不過的性能追蹤,咱們直接跳過,看else部分。

這裏面定義了一個updateComponent函數,涉及到兩個函數:

  • _render: 調用 vm.$options.render 函數並返回生成的虛擬節點( VNode
  • _update: 將 VNode 渲染成真實 DOM

這裏我只是大概說明一下它的做用,具體會在後面章節中展開。

接着往下看:

// 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 && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
複製代碼

這裏建立了一個 Watcher 實例,顯然是與響應式數據相關的。這裏的 Watcher 也僅作了解,在後面的章節會具體分析。

Watcher 會解析表達式,收集依賴關係,而且在表達式的值發生改變時觸發回調。Watcher 在這裏主要有兩個做用: 一個是初始化的時候會執行回調函數;另外一個是當 vm 實例中監測的數據發生變化的時候執行回調函數,而回調函數就是傳入的 updateComponent 函數。

回到 mountComponent 函數,還剩最後一段代碼:

// 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
複製代碼

函數最後判斷爲根節點的時候設置 vm._isMountedtrue, 表示這個實例已經掛載了,同時執行 mounted 鉤子函數。

這裏注意 vm.$vnode 表示 Vue 實例的父虛擬 Node,因此它爲 Null 則表示當前是根 Vue 的實例。

總結

這一節咱們分析了 $mount 函數的大致執行流程,下一篇文章我將介紹 $mount 函數中_render 函數的實現。

相關文章
相關標籤/搜索