Vue.js 的核心是一个允许采用简洁的模板语法来声明式地将数据渲染进DOM的系统

1
2
3
<div id="app">
{{ message }}
</div>
1
2
3
4
5
6
var app = new Vue({
el: '#app',
data: {
message: 'Hello world'
}
})

那么,数据是如何渲染进DOM系统的呢?先来看new Vue()是怎么实现的

vue.js为例,在scripts/config.js中可以看到

1
2
3
4
5
6
7
8
9
10
11
12
const builds = {
// code ...
// Runtime+compiler development build (Browser)
'web-full-dev': {
entry: resolve('web/entry-runtime-with-compiler.js'),
dest: resolve('dist/vue.js'),
format: 'umd',
env: 'development',
alias: { he: './entity-decoder' },
banner
},
// code ...

打开入口文件src/platforms/web/entry-runtime-with-compiler.js,其中有

1
import Vue from './runtime/index'

继续打开src/platforms/web/runtime/index.js

1
import Vue from 'core/index'

接着打开src/core/index.js

1
import Vue from './instance/index'

最终可以在src/core/instance/index.js中找到Vue的构造函数,整个过程是这样的

  1. src/platforms/web/entry-runtime-with-compiler.js

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

  3. src/core/index.js

  4. src/core/instance/index.js

Vue的构造函数如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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'

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

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

首先引入相关的调用函数,然后定义了一个类,分别调用initMixin(Vue)stateMixin(Vue)等五个方法初始化这个类的功能,最后导出

分别找到这五个方法,简单的看一下就可以发现,这些方法的作用就是在Vue的原型上挂载方法和属性

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
// initMixin(Vue)
Vue.prototype._init = function (options?: Object) { ... }

// stateMixin(Vue)
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)
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)
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) { ... }
Vue.prototype.$forceUpdate = function () { ... }
Vue.prototype.$destroy = function () { ... }

// renderMixin(Vue)
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._d = bindDynamicKeys
Vue.prototype._p = prependModifier
Vue.prototype.$nextTick = function (fn: Function) { ... }
Vue.prototype._render = function (): VNode { ... }

首先来看this._init(options)方法,这个方法定义在src/core/instance/init.jsinitMixin(Vue)

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
export function initMixin (Vue: Class<Component>) {
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()方法传入options作为参数,在完成部分属性设置后,首先执行一个merge options的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Vue.prototype._init = function (options?: Object) {
// code ...
// 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
)
}
// code ...
}

可以看到options的合并场景有两种:

  • options是一个组件时,执行initInternalComponent(vm, options),这个分支主要用于子组件初始化

  • options不是组件时,通过调用mergeOptions来合并options,并设置为vm.$options,其中resolveConstructorOptions(vm.constructor)是这样的

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    export function resolveConstructorOptions (Ctor: Class<Component>) {
    let options = Ctor.options
    if (Ctor.super) {
    const superOptions = resolveConstructorOptions(Ctor.super)
    const cachedSuperOptions = Ctor.superOptions
    if (superOptions !== cachedSuperOptions) {
    // super option changed,
    // need to resolve new options.
    Ctor.superOptions = superOptions
    // check if there are any late-modified/attached options (#4976)
    const modifiedOptions = resolveModifiedOptions(Ctor)
    // update base extend options
    if (modifiedOptions) {
    extend(Ctor.extendOptions, modifiedOptions)
    }
    options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
    if (options.name) {
    options.components[options.name] = Ctor
    }
    }
    }
    return options
    }

    可以看出resolveConstructorOptions函数的目的主要是解构获取构造器的options,以及它们的构造器如果有更新扩展,需要及时更新到下级。

那么构造器组件,也就是vm.constructor或者说Vue,其options属性又从何而来?

core/index.js中有

1
2
3
4
5
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'

initGlobalAPI(Vue)
// code ...

打开core/global-api/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ASSET_TYPES } from 'shared/constants'
import builtInComponents from '../components/index'

export function initGlobalAPI (Vue: GlobalAPI) {
// code ...
Vue.options = Object.create(null)
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)
// code ...
}

这段代码主要作用是创建Vue.options对象,并遍历ASSET_TYPES的值作为其子对象属性名,最后再添加_base属性和一个builtInComponents内置组件

ASSET_TYPES定义在shared/constants.js中,很明显遍历后生成的子对象属性名为components directives filters

1
2
3
4
5
export const ASSET_TYPES = [
'component',
'directive',
'filter'
]

builtInComponents定义在core/components/index.js中,是内置的keep-alive组件

1
2
3
4
5
import KeepAlive from './keep-alive'

export default {
KeepAlive
}

继续看platforms/web/runtime/index.js,其中有如下代码

1
2
3
4
5
6
import platformDirectives from './directives/index'
import platformComponents from './components/index'

// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

platformDirectives相关的部分——platforms/web/runtime/directives/index.js

1
2
3
4
5
6
7
import model from './model'
import show from './show'

export default {
model,
show
}

platformComponents相关的部分——platforms/web/runtime/components/index.js

1
2
3
4
5
6
7
import Transition from './transition'
import TransitionGroup from './transition-group'

export default {
Transition,
TransitionGroup
}

上面这段代码主要是给Vue.options.directives添加model show属性,给Vue.options.components添加Transition TransitionGroup属性

经过以上几步,就可以生成完整的Vue.options

vue.optionsvue.options

回到Vue.prototype._init方法,我们可以看到,在合并完配置后,_init方法还进行了初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等操作,最后检测到如果有el属性,则调用vm.$mount方法挂载vm,挂载的目标就是把模板渲染成最终的DOM