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 = { '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 },
打开入口文件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
的构造函数,整个过程是这样的
src/platforms/web/entry-runtime-with-compiler.js
src/platforms/web/runtime/index.js
src/core/index.js
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 Vue.prototype._init = function (options?: Object ) { ... } 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 { ... } 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 { ... } Vue.prototype._update = function (vnode: VNode, hydrating?: boolean ) { ... } Vue.prototype.$forceUpdate = function ( ) { ... } Vue.prototype.$destroy = function ( ) { ... } 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.js
的initMixin(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 vm._uid = uid++ let startTag, endTag if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = `vue-perf-start:${vm._uid} ` endTag = `vue-perf-end:${vm._uid} ` mark(startTag) } vm._isVue = true if (options && options._isComponent) { initInternalComponent(vm, options) } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ) } if (process.env.NODE_ENV !== 'production' ) { initProxy(vm) } else { vm._renderProxy = vm } vm._self = vm initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate' ) initInjections(vm) initState(vm) initProvide(vm) callHook(vm, 'created' ) 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 ) { if (options && options._isComponent) { initInternalComponent(vm, options) } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ) } }
可以看到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) { Ctor.superOptions = superOptions const modifiedOptions = resolveModifiedOptions(Ctor) 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)
打开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 ) { Vue.options = Object .create(null ) ASSET_TYPES.forEach(type => { Vue.options[type + 's' ] = Object .create(null ) }) Vue.options._base = Vue extend(Vue.options.components, builtInComponents) }
这段代码主要作用是创建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' 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.options
回到Vue.prototype._init
方法,我们可以看到,在合并完配置后,_init
方法还进行了初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等操作,最后检测到如果有el
属性,则调用vm.$mount
方法挂载vm
,挂载的目标就是把模板渲染成最终的DOM