从入口文件开始

阅读源码从package.json文件开始。这里面包含了项目的依赖、开发环境、生产环境等编译的启动脚本等信息。
这里我们只看npm run dev所执行的命令。

  1. "dev": "rollup -w -c build/config.js --environment TARGET:web-full-dev"

这里用到了rollup的打包工具,执行了build/config.js

  1. const builds = {
  2. ...
  3. ...
  4. ...
  5. // Runtime+compiler development build (Browser)
  6. 'web-full-dev': {
  7. entry: resolve('web/entry-runtime-with-compiler.js'),
  8. dest: resolve('dist/vue.js'),
  9. format: 'umd',
  10. env: 'development',
  11. alias: { he: './entity-decoder' },
  12. banner
  13. },
  14. ...
  15. ...
  16. ...
  17. }
  18. function genConfig (opts) {
  19. ...
  20. }
  21. if (process.env.TARGET) {
  22. module.exports = genConfig(builds[process.env.TARGET])
  23. } else {
  24. exports.getBuild = name => genConfig(builds[name])
  25. exports.getAllBuilds = () => Object.keys(builds).map(name => genConfig(builds[name]))
  26. }

根据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文件,在该文件中看到如下代码:

  1. import Vue from './runtime/index'

根据runtime/index文件,我们看到如下代码:

  1. import Vue from 'core/index'

之后的逻辑都是对Vue这个对象做一些扩展,暂时先不用看,我们看一下真正初始化Vue的地方,在src/core/index.js 中:

  1. import Vue from './instance/index'
  2. import { initGlobalAPI } from './global-api/index'
  3. import { isServerRendering } from 'core/util/env'
  4. import { FunctionalRenderContext } from 'core/vdom/create-functional-component'
  5. initGlobalAPI(Vue)
  6. Object.defineProperty(Vue.prototype, '$isServer', {
  7. get: isServerRendering
  8. })
  9. Object.defineProperty(Vue.prototype, '$ssrContext', {
  10. get () {
  11. /* istanbul ignore next */
  12. return this.$vnode && this.$vnode.ssrContext
  13. }
  14. })
  15. // expose FunctionalRenderContext for ssr runtime helper installation
  16. Object.defineProperty(Vue, 'FunctionalRenderContext', {
  17. value: FunctionalRenderContext
  18. })
  19. Vue.version = '__VERSION__'
  20. export default Vue

这里有两处关键代码:import Vue from ‘./instance/index’ 和 initGlobalAPI(Vue),初始化全局 Vue API之后再介绍。
在 src/core/instance/index.js 中,找到了定义Vue对象的所在之处。
回顾整个过程:
**234.png

Vue的定义

1.先看看 /src/core/instance/index.js 文件:
instance目录结构如下:

  1. |-- instance
  2. | |-- render-helpers # render渲染相关的工具函数目录
  3. | |-- events.js # 事件处理相关,例如:$on,$off,$emit以及$once等方法的实现。
  4. | |-- init.js # _init等方法相关,包含了Vue从创建实例到实例挂载阶段的所有主要逻辑。
  5. | |-- inject.js # inject和provide相关
  6. | |-- lifecycle.js # 生命周期相关,例如:$destroy、$activated和$deactivated。
  7. | |-- proxy.js # 代理相关
  8. | |-- render.js # 渲染相关,Vue.prototype._render渲染函数的定义。
  9. | |-- state.js # 数据状态相关,例如:data、props以及computed等。
  10. | |-- index.js # 入口文件

首先看入口文件:

  1. import { initMixin } from './init'
  2. import { stateMixin } from './state'
  3. import { renderMixin } from './render'
  4. import { eventsMixin } from './events'
  5. import { lifecycleMixin } from './lifecycle'
  6. import { warn } from '../util/index'
  7. //首先判断如果是不是生产环境,且不是通过new关键字来创建对象的话(instanceof操作符来判断实例的父类是否为Vue构造函数),就在控制台打印一个warning,之后调用了this._init(options)函数。
  8. function Vue (options) {
  9. if (process.env.NODE_ENV !== 'production' &&
  10. !(this instanceof Vue)
  11. ) {
  12. warn('Vue is a constructor and should be called with the `new` keyword')
  13. }
  14. this._init(options)
  15. }
  16. initMixin(Vue)
  17. stateMixin(Vue)
  18. eventsMixin(Vue)
  19. lifecycleMixin(Vue)
  20. renderMixin(Vue)
  21. export default Vue

Vue实际上就是一个用 Function 实现的类,我们只能通过 new Vue去实例化。

为何 Vue 不用 ES6 的 Class 去实现呢?我们往后看这里有很多 xxxMixin 的函数调用,并把 Vue 当参数传入,它们的功能都是给 Vue 的 prototype 上扩展一些方法(这里具体的细节会在之后的文章介绍,这里不展开),Vue 按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式是用 Class 难以实现的。这么做的好处是非常方便代码的维护和管理,这种编程技巧也非常值得我们去学习。

下面的几个函数,分别在Vue.prototype原型上绑定了一些实例方法。

  1. // _init
  2. initMixin(Vue)
  3. // $set、$delete、$watch
  4. stateMixin(Vue)
  5. // $on、$once、$off、$emit
  6. eventsMixin(Vue)
  7. // _update、$forceUpdate、$destroy
  8. lifecycleMixin(Vue)
  9. // $nextTick、_render、以及多个内部调用的方法
  10. renderMixin(Vue)

从以上代码中得到src/core/instance/index.js文件非常直观的代码逻辑流程图:(图来自initMixin流程)
instance.7ed3e2cf.png
initMixin
接着来了解_init()函数的代码逻辑及initMixin的整体流程。

  1. // 在构造函数内部会调用this._init()方法
  2. // 实例化时,会调用this._init()方法。
  3. new Vue({
  4. data: {
  5. msg: 'Hello, Vue.js'
  6. }
  7. })

在init.js中可以看到intiMixin()方法是如何被定义的:

  1. export function initMixin (Vue) {
  2. Vue.prototype._init = function (options) {
  3. // 省略代码
  4. }
  5. }


initMixin()方法主要作用是在Vue的原型上增加_init方法,构造Vue实例的时候会调用这个_init方法来初始化Vue实例
看一下_init()函数的具体实现逻辑:

  1. Vue.prototype._init = function (options) {
  2. const vm = this
  3. // 1. 合并配置
  4. if (options && options._isComponent) {
  5. initInternalComponent(vm, options)
  6. } else {
  7. vm.$options = mergeOptions(
  8. resolveConstructorOptions(vm.constructor),
  9. options || {},
  10. vm
  11. )
  12. }
  13. // 2.render代理
  14. if (process.env.NODE_ENV !== 'production') {
  15. initProxy(vm)
  16. } else {
  17. vm._renderProxy = vm
  18. }
  19. // 3.初始化生命周期、初始化事件中心、初始化inject,
  20. // 初始化state、初始化provide、调用生命周期
  21. vm._self = vm
  22. initLifecycle(vm) /*初始化生命周期*/
  23. initEvents(vm) /*初始化事件*/
  24. initRender(vm) /*初始化render*/
  25. callHook(vm, 'beforeCreate') /*调用beforeCreate钩子函数并且触发beforeCreate钩子事件*/
  26. initInjections(vm) // resolve injections before data/props
  27. initState(vm) /*初始化props、methods、data、computed与watch*/
  28. initProvide(vm) // resolve provide after data/props
  29. callHook(vm, 'created') /*调用created钩子函数并且触发created钩子事件*/
  30. // 4.挂载
  31. if (vm.$options.el) {
  32. vm.$mount(vm.$options.el)
  33. }
  34. }

initMixin.9a4f8f37.png
stateMixin
stateMixin主要是处理跟实例相关的属性和方法,它会在Vue.prototype上定义实例会使用到的属性或者方法。
src/core/instance/state.js代码:

  1. import { set, del } from '../observer/index'
  2. export function stateMixin (Vue) {
  3. // 定义$data, $props
  4. const dataDef = {}
  5. dataDef.get = function () { return this._data }
  6. const propsDef = {}
  7. propsDef.get = function () { return this._props }
  8. Object.defineProperty(Vue.prototype, '$data', dataDef)
  9. Object.defineProperty(Vue.prototype, '$props', propsDef)
  10. // 定义$set, $delete, $watch
  11. Vue.prototype.$set = set
  12. Vue.prototype.$delete = del
  13. Vue.prototype.$watch = function() {}
  14. }

stateMixin()方法中在Vue.prototype上定义的几个和响应式相关的属性或者方法:

$data和$props:根据以上代码,我们发现$data和$props分别是_data和_props的访问代理,从命名中我们可以推测,以下划线开头的变量,我们一般认为是私有变量,然后通过$data和$props来提供一个对外的访问接口,虽然可以通过属性的get()方法去取,但对于这两个私有变量来说是并不能随意set,对于data来说不能替换根实例,而对于props来说它是只读的。因此在原版源码中,还劫持了set()方法,当设置$data或者$props时会报错

  1. if (process.env.NODE_ENV !== 'production') {
  2. dataDef.set = function () {
  3. warn(
  4. 'Avoid replacing instance root $data. ' +
  5. 'Use nested data properties instead.',
  6. this
  7. )
  8. }
  9. propsDef.set = function () {
  10. warn(`$props is readonly.`, this)
  11. }
  12. }
  • $set和$delete:set和delete这两个方法被定义在跟instance目录平级的observer目录下,在stateMixin()中,它们分别赋值给了$set和$delete方法,而在initGlobalAPI中,也同样使用到了这两个方法,只不过一个是全局方法,一个是实例方法。
  • $watch:在stateMixin()方法中,详细实现了$watch()方法,此方法实现的核心是通过一个watcher实例来监听。当取消监听时,同样是使用watcher实例相关的方法,关于watcher在后续响应式章节详细介绍。
  1. Vue.prototype.$watch = function (
  2. expOrFn: string | Function,
  3. cb: any,
  4. options?: Object
  5. ): Function {
  6. const vm: Component = this
  7. if (isPlainObject(cb)) {
  8. return createWatcher(vm, expOrFn, cb, options)
  9. }
  10. options = options || {}
  11. options.user = true
  12. const watcher = new Watcher(vm, expOrFn, cb, options)
  13. if (options.immediate) {
  14. try {
  15. cb.call(vm, watcher.value)
  16. } catch (error) {
  17. handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)
  18. }
  19. }
  20. return function () {
  21. watcher.teardownunwatchFn()
  22. }
  23. }

stateMixin如下流程图:(图来自initMixin流程)
stateMixin.648e712c.png
eventsMixin
eventsMixin主要做的就是在Vue.prototype上定义这四个实例方法:$emit、$on、$off和$once

  1. export function eventsMixin (Vue) {
  2. // 定义$on
  3. Vue.prototype.$on = function (event, fn) {}
  4. // 定义$once
  5. Vue.prototype.$once = function (event, fn) {}
  6. // 定义$off
  7. Vue.prototype.$off = function (event, fn) {}
  8. // 定义$emit
  9. Vue.prototype.$emit = function (event) {}
  10. }

eventsMixin()所做的事情就是使用发布-订阅模式来处理事件。
$on方法的实现:

  1. Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {
  2. const vm: Component = this
  3. /*如果是数组的时候,则递归$on,为每一个成员都绑定上方法*/
  4. if (Array.isArray(event)) {
  5. for (let i = 0, l = event.length; i < l; i++) {
  6. vm.$on(event[i], fn)
  7. }
  8. } else {
  9. /* 所有$on的事件全部绑定在_events私有属性上,这个属性其实是在我们上面已经提到过的initEvents()方法中被定义的。*/
  10. (vm._events[event] || (vm._events[event] = [])).push(fn)
  11. // optimize hook:event cost by using a boolean flag marked at registration
  12. // instead of a hash lookup
  13. if (hookRE.test(event)) {
  14. vm._hasHookEvent = true
  15. }
  16. }
  17. return vm
  18. }

$emit方法的实现:

  1. /*触发一个事件方法*/
  2. Vue.prototype.$emit = function (event: string): Component {
  3. const vm: Component = this
  4. if (process.env.NODE_ENV !== 'production') {
  5. const lowerCaseEvent = event.toLowerCase()
  6. if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
  7. tip(
  8. `Event "${lowerCaseEvent}" is emitted in component ` +
  9. `${formatComponentName(vm)} but the handler is registered for "${event}". ` +
  10. `Note that HTML attributes are case-insensitive and you cannot use ` +
  11. `v-on to listen to camelCase events when using in-DOM templates. ` +
  12. `You should probably use "${hyphenate(event)}" instead of "${event}".`
  13. )
  14. }
  15. }
  16. //从_events对象中取出对应的cbs,接着一个个遍历cbs数组、调用并传参。
  17. let cbs = vm._events[event]
  18. if (cbs) {
  19. cbs = cbs.length > 1 ? toArray(cbs) : cbs
  20. const args = toArray(arguments, 1)
  21. const info = `event handler for "${event}"`
  22. for (let i = 0, l = cbs.length; i < l; i++) {
  23. //invokeWithErrorHandling代码中会使用try/catch把我们函数调用并执行的地方包裹起来,当函数调用出错时,会执行Vue的handleError()方法,这种做法不仅更加友好,而且对错误处理也非常有用。
  24. invokeWithErrorHandling(cbs[i], vm, args, vm, info)
  25. }
  26. }
  27. return vm
  28. }

vue中使用$emit和$on来配合测试事件的监听和触发:

  1. const app = new Vue()
  2. app.$on('eat', (food) => {
  3. console.log(`eating ${food}!`)
  4. })
  5. app.$emit('eat', 'orange')
  6. // eating orange!

$off的实现
$off方法的实现,相对来说比较复杂一点,因为它需要根据不同的传参做不同的事情:

  • 当没有提供任何参数时,移除全部事件监听。
  • 当只提供event参数时,只移除此event对应的监听器。
  • 同时提供event参数和fn回调,则只移除此event对应的fn这个监听器。
    1. /*注销一个事件,如果不传参则注销所有事件,如果只传event名则注销该event下的所有方法*/
    2. Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {
    3. const vm: Component = this
    4. // all
    5. /*如果不传参数则注销所有事件*/
    6. if (!arguments.length) {
    7. vm._events = Object.create(null)
    8. return vm
    9. }
    10. // array of events
    11. /*如果event是数组则递归注销事件*/
    12. if (Array.isArray(event)) {
    13. for (let i = 0, l = event.length; i < l; i++) {
    14. vm.$off(event[i], fn)
    15. }
    16. return vm
    17. }
    18. // specific event
    19. const cbs = vm._events[event]
    20. /*本身不存在该事件则直接返回*/
    21. if (!cbs) {
    22. return vm
    23. }
    24. /*如果只传了event参数则注销该event方法下的所有方法*/
    25. if (!fn) {
    26. vm._events[event] = null
    27. return vm
    28. }
    29. // specific handler
    30. /*遍历寻找对应方法并删除*/
    31. let cb
    32. let i = cbs.length
    33. while (i--) {
    34. cb = cbs[i]
    35. if (cb === fn || cb.fn === fn) {
    36. cbs.splice(i, 1)
    37. break
    38. }
    39. }
    40. return vm
    41. }
    $once的实现
    1. /*注册一个只执行一次的事件方法*/
    2. /*在源码中$once的实现是在回调函数中使用fn绑定了原回调函数的引用,在上面已经提到过的$off方法中也同样进行了cb.fn === fn的判断。*/
    3. Vue.prototype.$once = function (event: string, fn: Function): Component {
    4. const vm: Component = this
    5. function on () {
    6. vm.$off(event, on)
    7. fn.apply(vm, arguments)
    8. }
    9. on.fn = fn
    10. vm.$on(event, on)
    11. return vm
    12. }
    eventsMixin如下流程图:(图来自 eventsMixin流程 )
    eventsMixin.8ee82391.png

lifecycleMixin
lifecycleMixin主要是定义实例方法和生命周期,例如:$forceUpdate()、$destroy,另外它还定义一个_update的私有方法,其中$forceUpdate()方法会调用它

  1. export function lifecycleMixin (Vue) {
  2. // 私有方法:_update()会在组件渲染的时候调用
  3. Vue.prototype._update = function () {}
  4. // 实例方法:$forceUpdate()为一个强制Vue实例重新渲染的方法,它的内部调用了_update,也就是强制组件重选编译挂载。
  5. Vue.prototype.$forceUpdate = function () {
  6. if (this._watcher) {
  7. this._watcher.update()
  8. }
  9. }
  10. //$destroy()为组件销毁方法,在其具体的实现中,会处理父子组件的关系,事件监听,触发生命周期等操作。
  11. Vue.prototype.$destroy = function () {}
  12. }

lifecycleMixin如下流程图:(图来自 lifecycleMixin流程)
lifecycleMixin.9e3f413b.png
renderMixin
renderMixin主要在Vue.prototype上定义各种私有方法和一个非常重要的实例方法:$nextTick

  1. export function renderMixin (Vue) {
  2. // 挂载各种私有方法,例如this._n = toNumber、this._s = toString、this._v = createTextVNode和this._e = createEmptyVNode。
  3. installRenderHelpers(Vue.prototype)
  4. //_render()方法会把模板编译成VNode
  5. Vue.prototype._render = function () {}
  6. // nextTick会在Vue构造函数上挂载一个全局的nextTick()方法,而此处为实例方法,本质上引用的是同一个nextTick。
  7. Vue.prototype.$nextTick = function (fn) {
  8. return nextTick(fn, this)
  9. }
  10. }

renderMixin如下流程图:(图来自 renderMixin流程)
renderMixin.8c5372cd.png
2.沿着刚才所提到的文件引入顺序一步步来看。 /src/core/instance/index.js执行之后,是/src/core/index.js文件。

  1. initGlobalAPI(Vue)
  2. Object.defineProperty(Vue.prototype, '$isServer', {
  3. get: isServerRendering
  4. })
  5. Vue.version = '__VERSION__'

该文件首先调用了initGlobalAPI,引自/src/core/global-api/index。
initGlobalAPI()函数的作用是挂载一些全局API方法。
InitGlobalAPI.png
在 src/core/global-api 文件夹的目录结构如下:

  1. |-- global-api
  2. | |-- index.js # 入口文件
  3. | |-- assets.js # 挂载filter、component和directive
  4. | |-- extend.js # 挂载extend方法
  5. | |-- mixin.js # 挂载mixin方法
  6. | |-- use.js # 挂载use方法

在index.js入口文件中,我们能看到如下代码:

  1. export function initGlobalAPI (Vue: GlobalAPI) {
  2. // config
  3. const configDef = {}
  4. configDef.get = () => config
  5. if (process.env.NODE_ENV !== 'production') {
  6. configDef.set = () => {
  7. warn(
  8. 'Do not replace the Vue.config object, set individual fields instead.'
  9. )
  10. }
  11. }
  12. Object.defineProperty(Vue, 'config', configDef)
  13. // exposed util methods.
  14. // NOTE: these are not considered part of the public API - avoid relying on
  15. // them unless you are aware of the risk.
  16. Vue.util = {
  17. warn,
  18. extend,
  19. mergeOptions,
  20. defineReactive
  21. }
  22. Vue.set = set
  23. Vue.delete = del
  24. Vue.nextTick = nextTick
  25. // 2.6 explicit observable API
  26. Vue.observable = <T>(obj: T): T => {
  27. observe(obj)
  28. return obj
  29. }
  30. Vue.options = Object.create(null)
  31. // Vue.options.components、Vue.options.directives、Vue.options.filters
  32. config._assetTypes.forEach(type => {
  33. Vue.options[type + 's'] = Object.create(null)
  34. })
  35. // this is used to identify the "base" constructor to extend all plain-object
  36. // components with in Weex's multi-instance scenarios.
  37. // Vue.options._base
  38. Vue.options._base = Vue
  39. // Vue.options.components.KeepAlive
  40. extend(Vue.options.components, builtInComponents)
  41. // Vue.use
  42. initUse(Vue)
  43. // Vue.mixin
  44. initMixin(Vue)
  45. // Vue.extend
  46. initExtend(Vue)
  47. // Vue.component、Vue.directive、Vue.filter
  48. initAssetRegisters(Vue)
  49. }

/src/core/index.js文件中,还添加了一个Vue.prototype[$isServer]属性,用于判断是不是服务端渲染,还有一个就是Vue.version。
在index.js入口文件中,会在Vue构造函数上挂载各种全局API函数,其中set、delete、nextTick和observable直接赋值为一个函数,而其他几种API则是调用了一个以init开头的方法。
以initAssetRegisters()方法为例,它的代码如下:

  1. // ['component','directive', 'filter']
  2. import { ASSET_TYPES } from 'shared/constants'
  3. export function initAssetRegisters (Vue: GlobalAPI) {
  4. ASSET_TYPES.forEach(type => {
  5. Vue[type] = function () {
  6. // 省略了函数的参数和函数实现代码
  7. ....
  8. }
  9. })
  10. }

其中ASSET_TYPES是一个定义在src/shared/constants.js中的一个数组,然后在initAssetRegisters()方法中遍历这个数组,依次在Vue构造函数上挂载Vue.component()、Vue.directive()和Vue.filter()方法。
另外三种init开头的方法调用挂载对应的全局API:

  1. // initUse
  2. export function initUse(Vue) {
  3. Vue.use = function () {}
  4. }
  5. // initMixin
  6. export function initMixin(Vue) {
  7. Vue.mixin = function () {}
  8. }
  9. // initExtend
  10. export function initExtend(Vue) {
  11. Vue.extend = function () {}
  12. }

最后还有一个Vue.compile()方法,它其实是在runtime+compile版本才会有的一个全局方法,因此它在src/platforms/web/entry-runtime-with-compile.js中被定义:

  1. import Vue from './runtime/index'
  2. import { compileToFunctions } from './compiler/index'
  3. Vue.compile = compileToFunctions
  4. export default Vue

根据initGlobalAPI()方法的逻辑,可以得到如下流程图:(图来自initGlobalAPI流程)
initGlobalAPIProcess.6d78bbb9.png
3.接着是/src/entries/web-runtime.js

  1. // install platform specific utils
  2. Vue.config.mustUseProp = mustUseProp
  3. Vue.config.isReservedTag = isReservedTag
  4. Vue.config.getTagNamespace = getTagNamespace
  5. Vue.config.isUnknownElement = isUnknownElement
  6. // install platform runtime directives & components
  7. extend(Vue.options.directives, platformDirectives)
  8. extend(Vue.options.components, platformComponents)
  9. // install platform patch function
  10. Vue.prototype.__patch__ = inBrowser ? patch : noop
  11. // public mount method
  12. Vue.prototype.$mount = function (
  13. el?: string | Element,
  14. hydrating?: boolean
  15. ): Component {
  16. el = el && inBrowser ? query(el) : undefined
  17. return mountComponent(this, el, hydrating)
  18. }

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上。
在分析完从入口到构造函数的各个部分的流程后,我们可以得到一份大的流程图:(图来自整体流程)
process.8f86c136.png

总结

Vue整体流程时序图.png