从入口文件开始
阅读源码从package.json文件开始。这里面包含了项目的依赖、开发环境、生产环境等编译的启动脚本等信息。
这里我们只看npm run dev所执行的命令。
"dev": "rollup -w -c build/config.js --environment TARGET:web-full-dev"
这里用到了rollup的打包工具,执行了build/config.js
const builds = {.........// 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},.........}function genConfig (opts) {...}if (process.env.TARGET) {module.exports = genConfig(builds[process.env.TARGET])} else {exports.getBuild = name => genConfig(builds[name])exports.getAllBuilds = () => Object.keys(builds).map(name => genConfig(builds[name]))}
根据npm run dev所执行的命令,它调用了genConfig(builds[process.env.TARGET]), genConfig用于生成rollup的配置文件。
builds是一个对象,获取它的process.env.TARGET值,在package.json中,可以看到dev中有TARGET:web-full-dev参数,从而找到了入口文件 src/platforms/web/entry-runtime-with-compiler.js。
打开web-runtime-with-compiler.js文件,在该文件中看到如下代码:
import Vue from './runtime/index'
根据runtime/index文件,我们看到如下代码:
import Vue from 'core/index'
之后的逻辑都是对Vue这个对象做一些扩展,暂时先不用看,我们看一下真正初始化Vue的地方,在src/core/index.js 中:
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'initGlobalAPI(Vue)Object.defineProperty(Vue.prototype, '$isServer', {get: isServerRendering})Object.defineProperty(Vue.prototype, '$ssrContext', {get () {/* istanbul ignore next */return this.$vnode && this.$vnode.ssrContext}})// expose FunctionalRenderContext for ssr runtime helper installationObject.defineProperty(Vue, 'FunctionalRenderContext', {value: FunctionalRenderContext})Vue.version = '__VERSION__'export default Vue
这里有两处关键代码:import Vue from ‘./instance/index’ 和 initGlobalAPI(Vue),初始化全局 Vue API之后再介绍。
在 src/core/instance/index.js 中,找到了定义Vue对象的所在之处。
回顾整个过程:
**
Vue的定义
1.先看看 /src/core/instance/index.js 文件:
instance目录结构如下:
|-- instance| |-- render-helpers # render渲染相关的工具函数目录| |-- events.js # 事件处理相关,例如:$on,$off,$emit以及$once等方法的实现。| |-- init.js # _init等方法相关,包含了Vue从创建实例到实例挂载阶段的所有主要逻辑。| |-- inject.js # inject和provide相关| |-- lifecycle.js # 生命周期相关,例如:$destroy、$activated和$deactivated。| |-- proxy.js # 代理相关| |-- render.js # 渲染相关,Vue.prototype._render渲染函数的定义。| |-- state.js # 数据状态相关,例如:data、props以及computed等。| |-- index.js # 入口文件
首先看入口文件:
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'//首先判断如果是不是生产环境,且不是通过new关键字来创建对象的话(instanceof操作符来判断实例的父类是否为Vue构造函数),就在控制台打印一个warning,之后调用了this._init(options)函数。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
Vue实际上就是一个用 Function 实现的类,我们只能通过 new Vue去实例化。
为何 Vue 不用 ES6 的 Class 去实现呢?我们往后看这里有很多 xxxMixin 的函数调用,并把 Vue 当参数传入,它们的功能都是给 Vue 的 prototype 上扩展一些方法(这里具体的细节会在之后的文章介绍,这里不展开),Vue 按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式是用 Class 难以实现的。这么做的好处是非常方便代码的维护和管理,这种编程技巧也非常值得我们去学习。
下面的几个函数,分别在Vue.prototype原型上绑定了一些实例方法。
// _initinitMixin(Vue)// $set、$delete、$watchstateMixin(Vue)// $on、$once、$off、$emiteventsMixin(Vue)// _update、$forceUpdate、$destroylifecycleMixin(Vue)// $nextTick、_render、以及多个内部调用的方法renderMixin(Vue)
从以上代码中得到src/core/instance/index.js文件非常直观的代码逻辑流程图:(图来自initMixin流程)
initMixin
接着来了解_init()函数的代码逻辑及initMixin的整体流程。
// 在构造函数内部会调用this._init()方法// 实例化时,会调用this._init()方法。new Vue({data: {msg: 'Hello, Vue.js'}})
在init.js中可以看到intiMixin()方法是如何被定义的:
export function initMixin (Vue) {Vue.prototype._init = function (options) {// 省略代码}}
initMixin()方法主要作用是在Vue的原型上增加_init方法,构造Vue实例的时候会调用这个_init方法来初始化Vue实例
看一下_init()函数的具体实现逻辑:
Vue.prototype._init = function (options) {const vm = this// 1. 合并配置if (options && options._isComponent) {initInternalComponent(vm, options)} else {vm.$options = mergeOptions(resolveConstructorOptions(vm.constructor),options || {},vm)}// 2.render代理if (process.env.NODE_ENV !== 'production') {initProxy(vm)} else {vm._renderProxy = vm}// 3.初始化生命周期、初始化事件中心、初始化inject,// 初始化state、初始化provide、调用生命周期vm._self = vminitLifecycle(vm) /*初始化生命周期*/initEvents(vm) /*初始化事件*/initRender(vm) /*初始化render*/callHook(vm, 'beforeCreate') /*调用beforeCreate钩子函数并且触发beforeCreate钩子事件*/initInjections(vm) // resolve injections before data/propsinitState(vm) /*初始化props、methods、data、computed与watch*/initProvide(vm) // resolve provide after data/propscallHook(vm, 'created') /*调用created钩子函数并且触发created钩子事件*/// 4.挂载if (vm.$options.el) {vm.$mount(vm.$options.el)}}

stateMixin
stateMixin主要是处理跟实例相关的属性和方法,它会在Vue.prototype上定义实例会使用到的属性或者方法。
src/core/instance/state.js代码:
import { set, del } from '../observer/index'export function stateMixin (Vue) {// 定义$data, $propsconst dataDef = {}dataDef.get = function () { return this._data }const propsDef = {}propsDef.get = function () { return this._props }Object.defineProperty(Vue.prototype, '$data', dataDef)Object.defineProperty(Vue.prototype, '$props', propsDef)// 定义$set, $delete, $watchVue.prototype.$set = setVue.prototype.$delete = delVue.prototype.$watch = function() {}}
stateMixin()方法中在Vue.prototype上定义的几个和响应式相关的属性或者方法:
$data和$props:根据以上代码,我们发现$data和$props分别是_data和_props的访问代理,从命名中我们可以推测,以下划线开头的变量,我们一般认为是私有变量,然后通过$data和$props来提供一个对外的访问接口,虽然可以通过属性的get()方法去取,但对于这两个私有变量来说是并不能随意set,对于data来说不能替换根实例,而对于props来说它是只读的。因此在原版源码中,还劫持了set()方法,当设置$data或者$props时会报错
if (process.env.NODE_ENV !== 'production') {dataDef.set = function () {warn('Avoid replacing instance root $data. ' +'Use nested data properties instead.',this)}propsDef.set = function () {warn(`$props is readonly.`, this)}}
- $set和$delete:set和delete这两个方法被定义在跟instance目录平级的observer目录下,在stateMixin()中,它们分别赋值给了$set和$delete方法,而在initGlobalAPI中,也同样使用到了这两个方法,只不过一个是全局方法,一个是实例方法。
- $watch:在stateMixin()方法中,详细实现了$watch()方法,此方法实现的核心是通过一个watcher实例来监听。当取消监听时,同样是使用watcher实例相关的方法,关于watcher在后续响应式章节详细介绍。
Vue.prototype.$watch = function (expOrFn: string | Function,cb: any,options?: Object): Function {const vm: Component = thisif (isPlainObject(cb)) {return createWatcher(vm, expOrFn, cb, options)}options = options || {}options.user = trueconst watcher = new Watcher(vm, expOrFn, cb, options)if (options.immediate) {try {cb.call(vm, watcher.value)} catch (error) {handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)}}return function () {watcher.teardownunwatchFn()}}
stateMixin如下流程图:(图来自initMixin流程)
eventsMixin
eventsMixin主要做的就是在Vue.prototype上定义这四个实例方法:$emit、$on、$off和$once
export function eventsMixin (Vue) {// 定义$onVue.prototype.$on = function (event, fn) {}// 定义$onceVue.prototype.$once = function (event, fn) {}// 定义$offVue.prototype.$off = function (event, fn) {}// 定义$emitVue.prototype.$emit = function (event) {}}
eventsMixin()所做的事情就是使用发布-订阅模式来处理事件。
$on方法的实现:
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {const vm: Component = this/*如果是数组的时候,则递归$on,为每一个成员都绑定上方法*/if (Array.isArray(event)) {for (let i = 0, l = event.length; i < l; i++) {vm.$on(event[i], fn)}} else {/* 所有$on的事件全部绑定在_events私有属性上,这个属性其实是在我们上面已经提到过的initEvents()方法中被定义的。*/(vm._events[event] || (vm._events[event] = [])).push(fn)// optimize hook:event cost by using a boolean flag marked at registration// instead of a hash lookupif (hookRE.test(event)) {vm._hasHookEvent = true}}return vm}
$emit方法的实现:
/*触发一个事件方法*/Vue.prototype.$emit = function (event: string): Component {const vm: Component = thisif (process.env.NODE_ENV !== 'production') {const lowerCaseEvent = event.toLowerCase()if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {tip(`Event "${lowerCaseEvent}" is emitted in component ` +`${formatComponentName(vm)} but the handler is registered for "${event}". ` +`Note that HTML attributes are case-insensitive and you cannot use ` +`v-on to listen to camelCase events when using in-DOM templates. ` +`You should probably use "${hyphenate(event)}" instead of "${event}".`)}}//从_events对象中取出对应的cbs,接着一个个遍历cbs数组、调用并传参。let cbs = vm._events[event]if (cbs) {cbs = cbs.length > 1 ? toArray(cbs) : cbsconst args = toArray(arguments, 1)const info = `event handler for "${event}"`for (let i = 0, l = cbs.length; i < l; i++) {//invokeWithErrorHandling代码中会使用try/catch把我们函数调用并执行的地方包裹起来,当函数调用出错时,会执行Vue的handleError()方法,这种做法不仅更加友好,而且对错误处理也非常有用。invokeWithErrorHandling(cbs[i], vm, args, vm, info)}}return vm}
vue中使用$emit和$on来配合测试事件的监听和触发:
const app = new Vue()app.$on('eat', (food) => {console.log(`eating ${food}!`)})app.$emit('eat', 'orange')// eating orange!
$off的实现
$off方法的实现,相对来说比较复杂一点,因为它需要根据不同的传参做不同的事情:
- 当没有提供任何参数时,移除全部事件监听。
- 当只提供event参数时,只移除此event对应的监听器。
- 同时提供event参数和fn回调,则只移除此event对应的fn这个监听器。
$once的实现/*注销一个事件,如果不传参则注销所有事件,如果只传event名则注销该event下的所有方法*/Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {const vm: Component = this// all/*如果不传参数则注销所有事件*/if (!arguments.length) {vm._events = Object.create(null)return vm}// array of events/*如果event是数组则递归注销事件*/if (Array.isArray(event)) {for (let i = 0, l = event.length; i < l; i++) {vm.$off(event[i], fn)}return vm}// specific eventconst cbs = vm._events[event]/*本身不存在该事件则直接返回*/if (!cbs) {return vm}/*如果只传了event参数则注销该event方法下的所有方法*/if (!fn) {vm._events[event] = nullreturn vm}// specific handler/*遍历寻找对应方法并删除*/let cblet i = cbs.lengthwhile (i--) {cb = cbs[i]if (cb === fn || cb.fn === fn) {cbs.splice(i, 1)break}}return vm}
eventsMixin如下流程图:(图来自 eventsMixin流程 )/*注册一个只执行一次的事件方法*//*在源码中$once的实现是在回调函数中使用fn绑定了原回调函数的引用,在上面已经提到过的$off方法中也同样进行了cb.fn === fn的判断。*/Vue.prototype.$once = function (event: string, fn: Function): Component {const vm: Component = thisfunction on () {vm.$off(event, on)fn.apply(vm, arguments)}on.fn = fnvm.$on(event, on)return vm}

lifecycleMixin
lifecycleMixin主要是定义实例方法和生命周期,例如:$forceUpdate()、$destroy,另外它还定义一个_update的私有方法,其中$forceUpdate()方法会调用它
export function lifecycleMixin (Vue) {// 私有方法:_update()会在组件渲染的时候调用Vue.prototype._update = function () {}// 实例方法:$forceUpdate()为一个强制Vue实例重新渲染的方法,它的内部调用了_update,也就是强制组件重选编译挂载。Vue.prototype.$forceUpdate = function () {if (this._watcher) {this._watcher.update()}}//$destroy()为组件销毁方法,在其具体的实现中,会处理父子组件的关系,事件监听,触发生命周期等操作。Vue.prototype.$destroy = function () {}}
lifecycleMixin如下流程图:(图来自 lifecycleMixin流程)

renderMixin
renderMixin主要在Vue.prototype上定义各种私有方法和一个非常重要的实例方法:$nextTick
export function renderMixin (Vue) {// 挂载各种私有方法,例如this._n = toNumber、this._s = toString、this._v = createTextVNode和this._e = createEmptyVNode。installRenderHelpers(Vue.prototype)//_render()方法会把模板编译成VNodeVue.prototype._render = function () {}// nextTick会在Vue构造函数上挂载一个全局的nextTick()方法,而此处为实例方法,本质上引用的是同一个nextTick。Vue.prototype.$nextTick = function (fn) {return nextTick(fn, this)}}
renderMixin如下流程图:(图来自 renderMixin流程)
2.沿着刚才所提到的文件引入顺序一步步来看。 /src/core/instance/index.js执行之后,是/src/core/index.js文件。
initGlobalAPI(Vue)Object.defineProperty(Vue.prototype, '$isServer', {get: isServerRendering})Vue.version = '__VERSION__'
该文件首先调用了initGlobalAPI,引自/src/core/global-api/index。
initGlobalAPI()函数的作用是挂载一些全局API方法。
在 src/core/global-api 文件夹的目录结构如下:
|-- global-api| |-- index.js # 入口文件| |-- assets.js # 挂载filter、component和directive| |-- extend.js # 挂载extend方法| |-- mixin.js # 挂载mixin方法| |-- use.js # 挂载use方法
在index.js入口文件中,我们能看到如下代码:
export function initGlobalAPI (Vue: GlobalAPI) {// configconst configDef = {}configDef.get = () => configif (process.env.NODE_ENV !== 'production') {configDef.set = () => {warn('Do not replace the Vue.config object, set individual fields instead.')}}Object.defineProperty(Vue, 'config', configDef)// exposed util methods.// NOTE: these are not considered part of the public API - avoid relying on// them unless you are aware of the risk.Vue.util = {warn,extend,mergeOptions,defineReactive}Vue.set = setVue.delete = delVue.nextTick = nextTick// 2.6 explicit observable APIVue.observable = <T>(obj: T): T => {observe(obj)return obj}Vue.options = Object.create(null)// Vue.options.components、Vue.options.directives、Vue.options.filtersconfig._assetTypes.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._baseVue.options._base = Vue// Vue.options.components.KeepAliveextend(Vue.options.components, builtInComponents)// Vue.useinitUse(Vue)// Vue.mixininitMixin(Vue)// Vue.extendinitExtend(Vue)// Vue.component、Vue.directive、Vue.filterinitAssetRegisters(Vue)}
/src/core/index.js文件中,还添加了一个Vue.prototype[$isServer]属性,用于判断是不是服务端渲染,还有一个就是Vue.version。
在index.js入口文件中,会在Vue构造函数上挂载各种全局API函数,其中set、delete、nextTick和observable直接赋值为一个函数,而其他几种API则是调用了一个以init开头的方法。
以initAssetRegisters()方法为例,它的代码如下:
// ['component','directive', 'filter']import { ASSET_TYPES } from 'shared/constants'export function initAssetRegisters (Vue: GlobalAPI) {ASSET_TYPES.forEach(type => {Vue[type] = function () {// 省略了函数的参数和函数实现代码....}})}
其中ASSET_TYPES是一个定义在src/shared/constants.js中的一个数组,然后在initAssetRegisters()方法中遍历这个数组,依次在Vue构造函数上挂载Vue.component()、Vue.directive()和Vue.filter()方法。
另外三种init开头的方法调用挂载对应的全局API:
// initUseexport function initUse(Vue) {Vue.use = function () {}}// initMixinexport function initMixin(Vue) {Vue.mixin = function () {}}// initExtendexport function initExtend(Vue) {Vue.extend = function () {}}
最后还有一个Vue.compile()方法,它其实是在runtime+compile版本才会有的一个全局方法,因此它在src/platforms/web/entry-runtime-with-compile.js中被定义:
import Vue from './runtime/index'import { compileToFunctions } from './compiler/index'Vue.compile = compileToFunctionsexport default Vue
根据initGlobalAPI()方法的逻辑,可以得到如下流程图:(图来自initGlobalAPI流程)
3.接着是/src/entries/web-runtime.js
// install platform specific utilsVue.config.mustUseProp = mustUsePropVue.config.isReservedTag = isReservedTagVue.config.getTagNamespace = getTagNamespaceVue.config.isUnknownElement = isUnknownElement// install platform runtime directives & componentsextend(Vue.options.directives, platformDirectives)extend(Vue.options.components, platformComponents)// install platform patch functionVue.prototype.__patch__ = inBrowser ? patch : noop// public mount methodVue.prototype.$mount = function (el?: string | Element,hydrating?: boolean): Component {el = el && inBrowser ? query(el) : undefinedreturn mountComponent(this, el, hydrating)}
Vue代码整体上可以分为两个平台,一个是我们常用的web,另一个是weex。所以源码里把两个平台不同的内容单独提取出来了。这里我们只谈web。
首先,在Vue.config上添加了几个平台相关的方法,扩展了Vue.options.directives(model和show)和Vue.options.components(Transition和TransitionGroup)。在Vue.prototype上添加了patch(虚拟dom相关)和$mount(挂载元素)。
4. 最后是/src/entries/web-runtime-with-compiler.js
该文件主要干了两件事,一个是定义了一个方法Vue.prototype.$mount,另一个是将compileToFunctions挂在到Vue.compile上。
在分析完从入口到构造函数的各个部分的流程后,我们可以得到一份大的流程图:(图来自整体流程)
总结

