前端框架解决的根本问题就是数据和ui同步的问题,vue很好的额解决了那个问题。也就是Vue.js 一个核心思想是数据驱动。所谓数据驱动,是指视图是由数据驱动生成的,咱们对视图的修改,不会直接操做 DOM,而是经过修改数据。经过分析来弄清楚模板和数据如何渲染成最终的 DOM。html
从入口代码开始分析,咱们先来分析 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
打开 ./init.js 文件,找到 initMixin 方法,以下:vue
export function initMixin (Vue: Class<Component>) { Vue.prototype._init = function (options?: Object) { // ... _init 方法的函数体,此处省略 } }
这个方法的做用就是在 Vue 的原型上添加了 _init 方法,这个 _init 方法看上去应该是内部初始化的一个方法。在vue内部调用node
在 Vue 的构造函数里有这么一句:this._init(options),这说明,当咱们执行 new Vue() 的时候,this._init(options) 将被执行webpack
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 :ios
const dataDef = {} dataDef.get = function () { return this._data } const propsDef = {} propsDef.get = function () { return this._props }
能够看到,$data 属性实际上代理的是 _data 这个实例属性,而 $props 代理的是 _props 这个实例属性。而后有一个是否为生产环境的判断,若是不是生产环境的话,就为 $data 和 $props 这两个属性设置一下 set,实际上就是提示你一下:别他娘的想修改我,老子无敌。web
也就是说,$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 { // ... }
这个方法在 ./events.js 文件中,打开这个文件找到 eventsMixin 方法,这个方法在 Vue.prototype 上添加了四个方法,分别是:api
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 {}
打开 ./lifecycle.js 文件找到相应方法,这个方法在 Vue.prototype 上添加了三个方法:
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {} Vue.prototype.$forceUpdate = function () {} Vue.prototype.$destroy = function () {}
它在 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 { // ... 函数体 }
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
// 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
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 进行平台化地包装:
在看完 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 关键字在 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,便可开启性能追踪,你能够追踪四个场景的性能:
其中组件初始化的性能追踪就是咱们在 _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 中咱们是经过 $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
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 的概念.
真正的 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 方法建立的,咱们接下来分析这部分的实现。
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
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(container, vnode); 或 patch(vnode, newVnode);
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 }
具体分析看其余的文章
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 个参数
createElement 函数的流程略微有点多,咱们接下来主要分析 2 个重点的流程 —— children 的规范化以及 VNode 的建立。
因为 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
回到 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 完成的,接下来分析一下这个过程。
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 < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor) } ancestor.elm = vnode.elm if (patchable) { for (let i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, ancestor) } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. const insert = ancestor.data.hook.insert if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (let i = 1; i < insert.fns.length; i++) { insert.fns[i]() } } } else { registerRef(ancestor) } ancestor = ancestor.parent } } // destroy old node if (isDef(parentElm)) { removeVnodes(parentElm, [oldVnode], 0, 0) } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode) } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch) return vnode.elm } }
createPatchFunction 内部定义了一系列的辅助方法,最终返回了一个 patch 方法,这个方法就赋值给了 vm._update 函数里调用的 vm.__patch__。
在介绍 patch 的方法实现以前,咱们能够思考一下为什么 Vue.js 源码绕了这么一大圈,把相关代码分散到各个目录。由于前面介绍过,patch 是平台相关的,在 Web 和 Weex 环境,它们把虚拟 DOM 映射到 “平台 DOM” 的方法是不一样的,而且对 “DOM” 包括的属性模块建立和更新也不尽相同。所以每一个平台都有各自的 nodeOps 和 modules,它们的代码须要托管在 src/platforms 这个大目录下。
而不一样平台的 patch 的主要逻辑部分是相同的,因此这部分公共的部分托管在 core 这个大目录下。差别化部分只须要经过参数来区别,这里用到了一个函数柯里化的技巧,经过 createPatchFunction 把差别化参数提早固化,这样不用每次调用 patch 的时候都传递 nodeOps 和 modules 了,这种编程技巧也很是值得学习。
在这里,nodeOps 表示对 “平台 DOM” 的一些操做方法,modules 表示平台的一些模块,它们会在整个 patch 过程的不一样阶段执行相应的钩子函数。这些代码的具体实现会在以后的章节介绍。
回到 patch 方法自己,它接收 4个参数,oldVnode 表示旧的 VNode 节点,它也能够不存在或者是一个 DOM 对象;vnode 表示执行 _render 后返回的 VNode 的节点;hydrating 表示是不是服务端渲染;removeOnly 是给 transition-group 用的,以后会介绍。
patch 的逻辑看上去相对复杂,由于它有着很是多的分支逻辑,为了方便理解,咱们并不会在这里介绍全部的逻辑,仅会针对咱们以前的例子分析它的执行逻辑。以后咱们对其它场景作源码分析的时候会再次回顾 patch 方法。
先来回顾咱们的例子:
var app = new Vue({ el: '#app', render: function (createElement) { return createElement('div', { attrs: { id: 'app' }, }, this.message) }, data: { message: 'Hello Vue!' } })
而后咱们在 vm._update 的方法里是这么调用 patch 方法的:
// initial render vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
结合咱们的例子,咱们的场景是首次渲染,因此在执行 patch 函数的时候,传入的 vm.$el 对应的是例子中 id 为 app 的 DOM 对象,这个也就是咱们在 index.html 模板中写的
肯定了这些入参后,咱们回到 patch 函数的执行过程,看几个关键步骤。
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) ) }
因为咱们传入的 oldVnode 其实是一个 DOM container,因此 isRealElement 为 true,接下来又经过 emptyNodeAt 方法把 oldVnode 转换成 VNode 对象,而后再调用 createElm 方法,这个方法在这里很是重要,来看一下它的实现:
function createElm ( vnode, insertedVnodeQueue, parentElm, refElm, nested, ownerArray, index ) { if (isDef(vnode.elm) && isDef(ownerArray)) { // This vnode was used in a previous render! // now it's used as a new node, overwriting its elm would cause // potential patch errors down the road when it's used as an insertion // reference node. Instead, we clone the node on-demand before creating // associated DOM element for it. vnode = ownerArray[index] = cloneVNode(vnode) } vnode.isRootInsert = !nested // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } const data = vnode.data const children = vnode.children const tag = vnode.tag if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { creatingElmInVPre++ } if (isUnknownElement(vnode, creatingElmInVPre)) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ) } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode) setScope(vnode) /* istanbul ignore if */ if (__WEEX__) { // ... } else { createChildren(vnode, children, insertedVnodeQueue) if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue) } insert(parentElm, vnode.elm, refElm) } if (process.env.NODE_ENV !== 'production' && data && data.pre) { creatingElmInVPre-- } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text) insert(parentElm, vnode.elm, refElm) } else { vnode.elm = nodeOps.createTextNode(vnode.text) insert(parentElm, vnode.elm, refElm) } }
createElm 的做用是经过虚拟节点建立真实的 DOM 并插入到它的父节点中。 咱们来看一下它的一些关键逻辑,createComponent 方法目的是尝试建立子组件,这个逻辑在以后组件的章节会详细介绍,在当前这个 case 下它的返回值为 false;接下来判断 vnode 是否包含 tag,若是包含,先简单对 tag 的合法性在非生产环境下作校验,看是不是一个合法标签;而后再去调用平台 DOM 的操做去建立一个占位符元素。
vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode) 接下来调用 createChildren 方法去建立子元素: createChildren(vnode, children, insertedVnodeQueue) function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { if (process.env.NODE_ENV !== 'production') { checkDuplicateKeys(children) } for (let i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i) } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text))) } } createChildren 的逻辑很简单,其实是遍历子虚拟节点,递归调用 createElm,这是一种经常使用的深度优先的遍历算法,这里要注意的一点是在遍历过程当中会把 vnode.elm 做为父容器的 DOM 节点占位符传入。 接着再调用 invokeCreateHooks 方法执行全部的 create 的钩子并把 vnode push 到 insertedVnodeQueue 中。 if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (let i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode) } i = vnode.data.hook // Reuse variable if (isDef(i)) { if (isDef(i.create)) i.create(emptyNode, vnode) if (isDef(i.insert)) insertedVnodeQueue.push(vnode) } }
最后调用 insert 方法把 DOM 插入到父节点中,由于是递归调用,子元素会优先调用 insert,因此整个 vnode 树节点的插入顺序是先子后父。来看一下 insert 方法,它的定义在 src/core/vdom/patch.js 上。
insert(parentElm, vnode.elm, refElm) function insert (parent, elm, ref) { if (isDef(parent)) { if (isDef(ref)) { if (ref.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref) } } else { nodeOps.appendChild(parent, elm) } } } insert 逻辑很简单,调用一些 nodeOps 把子节点插入到父节点中,这些辅助方法定义在 src/platforms/web/runtime/node-ops.js 中: export function insertBefore (parentNode: Node, newNode: Node, referenceNode: Node) { parentNode.insertBefore(newNode, referenceNode) } export function appendChild (node: Node, child: Node) { node.appendChild(child) }
其实就是调用原生 DOM 的 API 进行 DOM 操做,看到这里,不少同窗恍然大悟,原来 Vue 是这样动态建立的 DOM。
在 createElm 过程当中,若是 vnode 节点不包含 tag,则它有多是一个注释或者纯文本节点,能够直接插入到父元素中。在咱们这个例子中,最内层就是一个文本 vnode,它的 text 值取的就是以前的 this.message 的值 Hello Vue!。
再回到 patch 方法,首次渲染咱们调用了 createElm 方法,这里传入的 parentElm 是 oldVnode.elm 的父元素,在咱们的例子是 id 为 #app div 的父元素,也就是 Body;实际上整个过程就是递归建立了一个完整的 DOM 树并插入到 Body 上。
最后,咱们根据以前递归 createElm 生成的 vnode 插入顺序队列,执行相关的 insert 钩子函数,这部份内容咱们以后会详细介绍。