在上一篇笔记中:Vuex 4源码学习笔记 - Vuex是怎么与Vue结合?(三)
我们复习了Vuex的使用方式,以及为什么要使用Vuex,同时看到了Vuex是如何与Vue去结合到一起的。
Vuex是通过Vue插件的方式,通过use函数将Vuex实例对象绑定到Vue中。
然后我们在页面或者组件中可以通过useStore
函数或者this.$store
两种方式在页面中访问到store实例。
首先创建Vuex实例的方式为调用createStore函数来调用
import {
createStore } from 'vuex'
export default createStore({
state: {
/**...**/ },
getters: {
/**...**/ },
actions: {
/**...**/ },
mutations: {
/**...**/ }
})
createStore函数的源代码,可以看到实际是new了一个Store类的对象
export function createStore (options) {
return new Store(options)
}
Store 构造函数
然后我们看到Store类的源代码,new的第一步首先就是调用constructor构造函数
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.`)
}
const {
/* 一个数组,包含应用在 store 上的插件方法。*/
plugins = [],
/* 使 Vuex store 进入严格模式,在严格模式下,任何 mutation 处理函数以外修改 Vuex state 都会抛出错误。*/
strict = false,
/* devtool插件状态*/
devtools
} = options
// store internal state -> store的内部状态
/* 用来判断严格模式下是否是用mutation修改state的 */
this._committing = false
/* 存放action */
this._actions = Object.create(null)
/* 存放action订阅器*/
this._actionSubscribers = []
/* 存放mutation */
this._mutations = Object.create(null)
/* 存放getter */
this._wrappedGetters = Object.create(null)
/* module收集器 */
this._modules = new ModuleCollection(options)
/* 根据namespace存放module */
this