Skip to content

3. createStore的时候做了什么

要在项目中使用vuex,需要创建一个store,并向store传递一些state或者mutations

js
  import { createApp } from 'vue';
  import { createStore } from 'vuex';

  const options = {
    state() {
      return {
        count: 0
      }
    },
    mutations: {
      increment(state) {
        state.count++
      }
    }
  }
  const store = createStore(options)
  const app = createApp({})

  app.use(store)

那么在createStore的过程中发生了什么呢?

位于core/packages/runtime-core/src/apiCreateApp.ts文件

首先先导出了createStore方法,该方法接收一个参数options,并且返回一个Store实例

js
  export function createStore (options) {
    return new Store(options)
  }

Store类(构造器)的constructor

  • 首先先对环境进行了判断、检测
js
export class Store {
  constructor (options = {}) {
    if (__DEV__) {
      assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)
      assert(this instanceof Store, `store must be called with the new operator.`)
    }
    // ..... dosomething
  }
}

通过__DEV__字段判断当前是否为开发环境,并对运行环境(是否存在Promise构造器)及运行方式(是否通过new方式创建)进行检测,如不符合条件则在控制台打印警告。

关于assert方法会有一篇文章用于解析vuex的util。

关于__DEV__

在vuex的源码中经常看见这个值。它是一个布尔值,用于表示当前的运行环境是否是开发模式。它定义在./rollup.config.js文件下,通过isBundlerBuild字段进行判断。

js
const isBundlerBuild = config.format !== 'iife' && !config.browser

// ... dosomething
__DEV__: isBundlerBuild
// ... dosomething
  • 接着定义了一些内部变量
js
  const {
    plugins = [],
    strict = false,
    devtools
  } = options

  this._committing = false
  // Object.create(null)的方法创建一个没有原型的空对象
  this._actions = Object.create(null)
  this._actionSubscribers = []
  this._mutations = Object.create(null)
  this._wrappedGetters = Object.create(null)
  this._modules = new ModuleCollection(options)
  this._modulesNamespaceMap = Object.create(null)
  this._subscribers = []
  this._makeLocalGettersCache = Object.create(null)
  this._scope = null
  this._devtools = devtools
  const store = this

先从options中取出了pluginsstrictdevtools三个值 根据官方文档:

  • plugins是一个数组,数组内的值要是一些函数,这些函数的唯一参数就是当前Store实例
  • strict是一个布尔值,如果为true,则进入严格模式,在严格模式下,任何mutation以外修改state的函数都会报错。
  • devtools:打开vuex实例的开发者模式

KESHAOYE-知识星球