执行import Vue from ‘vue’时代码入口是src/platforms/web/entry-runtime-with-compiler.js

Vue庐山真面目

image.png

  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. function Vue (options) {
  8. if (process.env.NODE_ENV !== 'production' &&
  9. !(this instanceof Vue)
  10. ) {
  11. warn('Vue is a constructor and should be called with the `new` keyword')
  12. }
  13. this._init(options)
  14. }
  15. initMixin(Vue)
  16. stateMixin(Vue)
  17. eventsMixin(Vue)
  18. lifecycleMixin(Vue)
  19. renderMixin(Vue)
  20. export default Vue

使用Function实现的类,只能通过new Vue去实例它

为何不用ES6的Class去实现呢?

代码后边有 xxxMixin 的函数调用,它们是在传入的参数Vue的prototype上扩展一些方法
Vue按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式使用Class难以实现
这么做的好处是非常方便代码的维护和管理

initGlobalAPI

给Vue对象本身扩展全局静态方法

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

Vue.utils暴露的方法最好不要依赖,它们经常会发生变化,是不稳定的