上一篇源码阅读讲到了,挂载的目标就是把模板渲染成最终的 DOM,那么,Vue 是如何实现实例挂载呢?

Vue 通过$mount方法挂载vm,在src/core/instance/init.js中,有

1
2
3
4
5
6
7
8
9
10
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// code ...

if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
}

$mount方法的实现和平台以及构建方式有关,以src/platforms/webentry-runtime-with-compiler.js的实现为例,在这个实现中,先通过mount保存定义在原型中的Vue.prototype.$mount,然后在对其进行改写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)

/* 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
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, {
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')
}
}
}
return mount.call(this, el, hydrating)
}

先对传入的el参数进行处理,el可能为字符串或者 HTML 元素对象

1
el = el && query(el)

可以看到,只要传入的el不为空(false),那么会返回query(el)query方法定义在src/platforms/web/util/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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方法返回 DOM 结构,若不存在,返回<div></div>,具体来说

1
<div id="app">{{ text }}</div>
1
2
3
4
5
6
7
8
9
10
11
var app = new Vue({
data: {
text: 'Hello World'
}
}).$mount('#app');
// 或者
var app = new Vue({
data: {
text: 'Hello World'
}
}).$mount(document.getElementById('app'));

在 console 中输入app.$el

1
2
3
app.$el

// <div id="app">Hello World</div>

$mount方法传入的参数el有一定的限制

  1. 当它是一个错误的字符串时

    1
    2
    3
    4
    5
    6
    7
    var app = new Vue({
    data: {
    text: 'Hello World'
    }
    }).$mount('asd');

    // [Vue warn]: Cannot find element: asd

    在 console 中,

    1
    2
    3
    app.$el

    // <div></div>
  2. 改写后的Vue.prototype.$mount规定了el不能挂载到body或者html

    1
    2
    3
    4
    5
    6
    7
    8
    // code ...
    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
    }
    // code ...

    举例来说

    1
    2
    3
    4
    5
    6
    7
    var app = new Vue({
    data: {
    text: 'Hello World'
    }
    }).$mount(document.body);

    // [Vue warn]: Do not mount Vue to <html> or <body> - mount to normal elements instead.
  3. 如果是一个错误的 Element,则el的值为 null,则通过src/core/instance/lifecycle.js中的mountComponent方法发出警告

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    export function mountComponent (
    vm: Component,
    el: ?Element,
    hydrating?: boolean
    ): Component {
    vm.$el = el
    if (...) {
    // code ...
    }
    else {
    warn(
    'Failed to mount component: template or render function not defined.',
    vm
    )
    }
    // code ...
    }

    举例来看

    1
    2
    3
    4
    5
    6
    7
    var app = new Vue({
    data: {
    text: 'Hello World'
    }
    }).$mount(document.getElementById('asd'));

    // [Vue warn]: Failed to mount component: template or render function not defined.

当获取了正确的el后,如果options.render不存在,则将el或者template转换为render方法

首先判断options中是否有template属性,若存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// code ...
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
}
}
// code ...
  • 如果template是字符串类型,则必须以#开头,然后通过idToTemplate方法提取<template>...</template>中的 DOM 结构

    1
    2
    3
    4
    const idToTemplate = cached(id => {
    const el = query(id)
    return el && el.innerHTML
    })

    举例来说:

    1
    2
    3
    4
    5
    <div id="app">{{ text }}</div>

    <template id="asd">
    <p>{{ message }}</p>
    </template>
    1
    2
    3
    4
    5
    6
    7
    8
    var app = new Vue({
    el: '#app',
    data: {
    text: 'Hello World',
    message: 'Hello Vue'
    },
    template: '#asd'
    })

    在 console 中,

    1
    2
    3
    app.$el

    // <p>Hello Vue</p>
  • template也可以是 node 类型,上面的实例写成

    1
    2
    3
    4
    5
    6
    7
    8
    var app = new Vue({
    el: '#app',
    data: {
    text: 'Hello World',
    message: 'Hello Vue'
    },
    template: document.getElementById('asd')
    })

    也同样有效

如果不存在options.template属性,那么就通过传入的el及其子内容来生成template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// code ...
if (template) {
// code ...
} else if (el) {
template = getOuterHTML(el)
}
// code ...

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
}
}

经过以上两步之后可以确保template不为空,在通过compileToFunctions方法对最后生成的模板进行解析,生成render函数,最后调用最初缓存的原型上一开始定义的$mount方法进行挂载,该方法定义在src/platforms/web/runtime/index.js

1
2
3
4
5
6
7
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}

这个方法的核心是mountComponent方法,定义在src/core/instance/lifecycle.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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')

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)
}
}

// 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

// 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
}

该方法首先缓存了当前的 DOM,然后判断是否有render函数,如果没有则报错;

紧接着设置WathcerWatcher在这里起到两个作用,一个是初始化的时候会执行回调函数,另一个是当 vm 实例中的监测的数据发生变化的时候执行回调函数,这块儿在之后介绍

函数最后判断为根节点的时候设置vm._isMountedtrue,表示这个实例已经挂载了