src/core/instance/index.js

  1. function Vue (options) {
  2. if (process.env.NODE_ENV !== 'production' &&
  3. !(this instanceof Vue)
  4. ) {
  5. warn('Vue is a constructor and should be called with the `new` keyword')
  6. }
  7. this._init(options)
  8. }

src/core/instance/init.js

  1. Vue.prototype._init = function (options?: Object) {
  2. const vm: Component = this
  3. // a uid
  4. vm._uid = uid++
  5. let startTag, endTag
  6. /* istanbul ignore if */
  7. if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
  8. startTag = `vue-perf-start:${vm._uid}`
  9. endTag = `vue-perf-end:${vm._uid}`
  10. mark(startTag)
  11. }
  12. // a flag to avoid this being observed
  13. vm._isVue = true
  14. // merge options
  15. if (options && options._isComponent) {
  16. // optimize internal component instantiation
  17. // since dynamic options merging is pretty slow, and none of the
  18. // internal component options needs special treatment.
  19. initInternalComponent(vm, options)
  20. } else {
  21. vm.$options = mergeOptions(
  22. resolveConstructorOptions(vm.constructor),
  23. options || {},
  24. vm
  25. )
  26. }
  27. /* istanbul ignore else */
  28. if (process.env.NODE_ENV !== 'production') {
  29. initProxy(vm)
  30. } else {
  31. vm._renderProxy = vm
  32. }
  33. // expose real self
  34. vm._self = vm
  35. initLifecycle(vm)
  36. initEvents(vm)
  37. initRender(vm)
  38. callHook(vm, 'beforeCreate')
  39. initInjections(vm) // resolve injections before data/props
  40. initState(vm)
  41. initProvide(vm) // resolve provide after data/props
  42. callHook(vm, 'created')
  43. /* istanbul ignore if */
  44. if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
  45. vm._name = formatComponentName(vm, false)
  46. mark(endTag)
  47. measure(`vue ${vm._name} init`, startTag, endTag)
  48. }
  49. if (vm.$options.el) {
  50. vm.$mount(vm.$options.el)
  51. }
  52. }

总结

初始化时,把不同的功能逻辑拆成单独函数,是主线逻辑一目了然。