学习VUE源码(初始化流程一)

234 阅读1分钟

vue的构造函数在哪儿

在上一节课里根据示例代码,控制台打断点的方式找到 构造函数在 src/core/instance/index.js 中定义。

除此之外还阔以根据配置文件的入口 src/platform/web/entry-runtime-with-compiler.js 一步步寻找,在上一节中已经知道,entry-runtime-with-compiler.js 主要重写了vue原型的 $mount 方法。


src/platform/web/entry-runtime-with-compiler.js

  • 引用 './runtime/index'
import Vue from './runtime/index'
  • 重写 $mount 方法
...
Vue.prototype.$mount = function (
  el?: string | Element,
  // 非ssr情况下为 false,ssr 时候为true
  hydrating?: boolean
): Component {
  // 获取 el 对象
  el = el && query(el)

  /* istanbul ignore if */
  // el 不能是 body 或者 html
  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
  // 把 template/el 转换成 render 函数
  if (!options.render) {
    ... ...
  }
  // 调用 mount 方法,渲染 DOM
  return mount.call(this, el, hydrating)
}
  ...
  • 给vue注册compile属性
...
import { compileToFunctions } from './compiler/index'
...
Vue.compile = compileToFunctions

export default Vue

src/platform/web/runtime/index

/* @flow */

import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { mountComponent } from 'core/instance/lifecycle'
import { devtools, inBrowser } from 'core/util/index'

import {
  query,
  mustUseProp,
  isReservedTag,
  isReservedAttr,
  getTagNamespace,
  isUnknownElement
} from 'web/util/index'

import { patch } from './patch'
import platformDirectives from './directives/index'
import platformComponents from './components/index'

// install platform specific utils
// 判断是否是关键属性(表单元素的 input/checked/selected/muted)
// 如果是这些属性,设置el.props属性(属性不设置到标签上)
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// 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)
}

// devtools global hook
/* istanbul ignore next */
//调试相关的代码
if (inBrowser) {...
}

export default Vue
  • 在vue.config注册全局组件 Transition和 TransitionGroup
  • 在vue.config注册全局指令 v-model和 v-show
import { extend, noop } from 'shared/util'

import platformDirectives from './directives/index'
import platformComponents from './components/index'

// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
//  src/platform/web/runtime/components/index
import Transition from './transition'
import TransitionGroup from './transition-group'

export default {
  Transition,
  TransitionGroup
}
//  src/platform/web/runtime/directives/index
import model from './model'
import show from './show'

export default {
  model,
  show
}

具体实现以后再看,先捋清楚vue的初始化过程即可

  • 在vue原型挂载patch函数
import { patch } from './patch'

// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop

patch 函数的作用是将虚拟dom转化为真实节点,如果当前环境是浏览器,挂载patch

  • 在vue原型上定义 $mount
// public mount method
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

mountComponent函数是渲染dom

\

src/core/index

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)

// SSR相关
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 installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
  value: FunctionalRenderContext
})

Vue.version = '__VERSION__'

export default Vue
  • 调用initGlobalAPI用来定义静态方法
  • 给vue原型设置SSR相关的变量

根据core/index 的引用查看 vue 引入的文件

src/instance/index

这里就是vue构造函数定义的地方

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'
// 此处不用 class 的原因是因为方便后续给 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')
  }
  // 调用 _init() 方法
  this._init(options)
}
// 注册 vm 的 _init() 方法,初始化 vm
initMixin(Vue)
// 注册 vm 的 $data/$props/$set/$delete/$watch
stateMixin(Vue)
// 初始化事件相关方法
// $on/$once/$off/$emit
eventsMixin(Vue)
// 初始化生命周期相关的混入方法
// _update/$forceUpdate/$destroy
lifecycleMixin(Vue)
// 混入 render
// $nextTick/_render
renderMixin(Vue)

export default Vue
  • 定义vue的构造函数
  • 定义vue实例成员

为什么要用构造函数创建vue而不是class ??

为何 Vue 不用 ES6 的 Class 去实现呢?可以看到构造函数的下方执行了很多 xxxMixin 的函数调用,并把 Vue 当参数传入,它们的功能都是给 Vue 的 prototype 上扩展一些方法,Vue 按功能把这些扩展分散到多个模块中去实现,而不是在一个模块里实现所有,这种方式是用 Class 难以实现的。这么做的好处是非常方便代码的维护和管理,这种编程技巧也非常值得我们去学习。

总结以上四个导出vue的模块

  • src/platforms/web/entry-runtime-with-compiler.js
    • web 平台相关的入口
    • 重写了平台相关的 $mount() 方法
    • 注册了 Vue.compile() 方法,传递一个 HTML 字符串返回 render 函数
  • src/platforms/web/runtime/index.js
    • web 平台相关
    • 注册和平台相关的全局指令:v-model、v-show
    • 注册和平台相关的全局组件: v-transition、v-transition-group
    • 全局方法:
      • patch:把虚拟DOM转为真实DOM
      • 定义 $mount 方法
  • src/core/index.js
    • 与平台无关
    • 设置Vue的静态方法(执行initGlobalAPI函数)
  • src/core/instance/index.js
    • 与平台无关
    • 定义 Vue的构造函数,调用了 this._int(options) 方法
    • 给 Vue中混入常用的实例成员