Vue源码阅读(4):从入口文件开始,看 Vue 变量的初始化过程

 我的开源库:

我们在平时的开发中,一般是使用下面的代码使用 Vue:

import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: '#app',
  data() {
    return {}
  },
  render: h => h(App)
})

那么,你肯定有过这样的疑问,这个导入的 Vue 到底是什么?它是怎么初始化的呢?今天的这篇博客就来解答这个疑问。

1,src/platforms/web/entry-runtime-with-compiler.js

从上一篇博客可知,Vue 编译的入口在 src/platforms 里面。我们分析 web 版本下 Runtime + Compiler 的版本,从 entry-runtime-with-compiler.js 文件看起。上面代码中导入的 Vue 就是从该文件中导出的。 

import Vue from './runtime/index'
import { compileToFunctions } from './compiler/index'

// 当前的版本是 compiler 加上 runtime 的完整版,

// 这里的 Vue 是从 './runtime/index' 中导入的,在 './runtime/index' 中,Vue.prototype 中就已经定义了 $mount
// 这个已经定义了的 $mount 是适用于运行时环境的 $mount

// 而当前的版本是 compiler 加上 runtime 的完整版,所以在这里,取到这个 './runtime/index' 中已经定义了的 $mount
// 然后在下面定义的 $mount 函数的最后执行这个 mount 就可以了
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
      ... 进行模板字符串的编译工作 ...
  return mount.call(this, el, hydrating)
}

Vue.compile = compileToFunctions

export default Vue

从上面的代码我们可知:这个导出的 Vue 是从 ./runtime/index 中导入的。并且在该文件中,使用装饰器模式增强了 Vue 中的 $mount 函数。在下面,还给 Vue 赋值了一个全局 API compile。

Vue.compile() 函数的官方介绍如上图所示。

其中,有趣的一点是 "只在完整版时可用"。从上面源码的解读可知,这个 complie 函数是在 entry-runtime-with-compiler.js(完整版构建入口)中赋值给 Vue 的,在运行时版本的代码中并没有 complie 函数,我们从源码的角度印证了官方文档中的说法。

 2,接下来看 src/platforms/web/runtime/index.js

src/platforms/web/runtime/index.js 是运行时版本 Vue 的构建入口,代码如下:

/* @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, isChrome } 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'

// 安装与平台有关的工具函数(与平台相关是指:在不同的平台下,这些资源的实现方式是不同的)
Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isReservedAttr = isReservedAttr
Vue.config.getTagNamespace = getTagNamespace
Vue.config.isUnknownElement = isUnknownElement

// 安装与平台有关的运行时指令和组件
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// 渲染以及更新 DOM 时,调用的方法,很重要。这个函数也是与平台相关的。
Vue.prototype.__patch__ = inBrowser ? patch : noop

// 运行时版本代码使用的 $mount 函数。
// 调用这个 $mount 函数,模板字符串必须已经编译成 render 函数
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

export default Vue

在该文件中,给 Vue 赋值了一些与平台有关的工具函数、指令和组件,以及运行时代码的 $mount 函数。

3,src/core/index.js

src/core/index.js 定义 Vue 与平台无关的内容,代码如下:

import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'

// 挂载与平台无关的全局 API
initGlobalAPI(Vue)

Object.defineProperty(Vue.prototype, '$isServer', {
  get: isServerRendering
})

Object.defineProperty(Vue.prototype, '$ssrContext', {
  get () {
    /* istanbul ignore next */
    return this.$vnode && this.$vnode.ssrContext
  }
})

Vue.version = '__VERSION__'

export default Vue

主要的代码是 initGlobalAPI(Vue),我们看一下该函数的具体内容。

/* @flow */

import config from '../config'
import { initUse } from './use'
import { initMixin } from './mixin'
import { initExtend } from './extend'
import { initAssetRegisters } from './assets'
import { set, del } from '../observer/index'
import { ASSET_TYPES } from 'shared/constants'
import builtInComponents from '../components/index'

import {
  warn,
  extend,
  nextTick,
  mergeOptions,
  defineReactive
} from '../util/index'

export function initGlobalAPI (Vue: GlobalAPI) {
  // config
  const configDef = {}
  configDef.get = () => config
  if (process.env.NODE_ENV !== 'production') {
    configDef.set = () => {
      warn(
        'Do not replace the Vue.config object, set individual fields instead.'
      )
    }
  }
  Object.defineProperty(Vue, 'config', configDef)

  // 应用于 Vue 源码内部的工具函数,不建议程序员直接使用。
  Vue.util = {
    warn,
    extend,
    mergeOptions,
    defineReactive
  }

  // 定义全局 API。set、delete、nextTick
  Vue.set = set
  Vue.delete = del
  Vue.nextTick = nextTick

  // 定义 options 对象,该对象用于存储一系列的资源,如:组件、指令和过滤器
  Vue.options = Object.create(null)
  ASSET_TYPES.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._base = Vue

  // 将与平台无关的内建组件存储到 options.components 中
  extend(Vue.options.components, builtInComponents)

  // 初始化 Vue.use()
  initUse(Vue)
  // 初始化 Vue.mixin()
  initMixin(Vue)
  // 初始化 Vue.extend()
  initExtend(Vue)
  // 初始化 Vue.component()、Vue.directive()、Vue.filter(),用于向 Vue 中注册资源
  initAssetRegisters(Vue)
}

在 initGlobalAPI 函数中,初始化与平台无关的全局 API。例如:Vue.set()、Vue.delete()、Vue.use()、Vue.mixin()、Vue.extend() 等等。

4,src/core/instance/index.js

src/core/instance/index.js 是定义 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'

function Vue (options) {
  // 如果当前的环境不是生产环境,并且当前命名空间中的 this 不是 Vue 的实例的话
  // 发出警告,Vue 必须通过 new Vue({}) 使用,而不是把 Vue 当做函数使用
  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)
}

// 下面函数的作用是:往 Vue 的原型上写入原型函数,这些函数是给 Vue 的实例使用的
// 这些函数分为两类:一类是 Vue 内部使用的,特征是函数名以 '_' 开头;
//                 还有一类是给用户使用的,特征是函数名以 '$' 开头,这些函数可以在 Vue 的官方文档中看到;
// 写入 vm._init
initMixin(Vue)
// 写入 vm.$set、vm.$delete、vm.$watch
stateMixin(Vue)
// 写入 vm.$on、vm.$once、vm.$off、vm.$emit
eventsMixin(Vue)
// 写入 vm._update、vm.$forceUpdate、vm.$destroy
lifecycleMixin(Vue)
// 写入 vm.$nextTick、vm._render
renderMixin(Vue)

export default Vue


从上面代码可知,这个 Vue 变量本身并不是什么特别神奇的东西,它只不过是 Javascript 中一个极为普通的构造函数,我们可以通过 new Vue(options) 来使用它。

声明 Vue 构造函数后,将 Vue 作为参数执行一系列的函数,执行这些函数的作用是向 Vue 的原型对象中写入原型函数,这些函数是给 Vue 的实例使用的,例如:vm.$set、vm.$watch、vm.$emit 等等。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值