在上一篇笔记中:Vuex 4源码学习笔记 - Store 构造函数都干了什么(四)
我们通过查看Store 构造函数的源代码可以看到主要做了三件事情:
- 初始化一些内部变量以外
- 执行installModule来初始化module以及子module,
- 执行resetStoreState函数通过Vue3的reactive使store的状态实现“响应式”)。
今天我们我们通过官方的购物车示例来查看Vuex内部的工作流程,示例代码在examples/composition/shopping-cart
文件夹内
Vuex配置代码如下:
import {
createStore, createLogger } from 'vuex'
import cart from './modules/cart'
import products from './modules/products'
const debug = process.env.NODE_ENV !== 'production'
export default createStore({
modules: {
cart,
products
},
strict: debug,
plugins: debug ? [createLogger()] : []
})
Vuex组件module中各模块state配置代码部分:
/**
cart.js
*/
const state = {
items: [],
checkoutStatus: null
}
/**
products.js
*/
const state = {
all: []
}
页面加载成功后可以看到state和getters
state和getters都是按照配置中module path的规则来划分的
然后我们看在ProductList.vue组件中,通过store.dispatch方法来调用vuex中actions,其他不重要的代码省略了。
<script>
import {
useStore } from 'vuex'
export default {
setup () {
const store = useStore()
//...
store.dispatch('products/getAllProducts')
//...
}
}
</script>
这是products.js中的actions
const actions = {
getAllProducts ({
commit }) {
shop.getProducts(products => {
commit('setProducts', products)
})
}
}
第一步:store.dispatch将走到Store 构造函数内的this.dispatch函数
this.dispatch
重写了Store类的原型prototype上的dispatch方法,根据优先级规则,会优先找实例上的属性方法,再去找prototype原型上的属性方法。
/* 将dispatch与commit调用的this绑定为store对象本身*/
const store = this
const {
dispatch, commit } = this
this.dispatch = function boundDispatch (type, payload) {
return dispatch.call(store, type, payload)
}
第二步:dispatch.call将走到Store 的原型方法dispatch
dispatch (_type, _payload) {
//...
}
在dispatch函数内:
- 第一,首先通过
unifyObjectStyle
函数来抹平成统一化的参数,因为actions和mutation都支持两种参数方式调用
// check object-style dispatch
// 抹平数据格式,dispatch调用可能是以载荷形式分发,也可能是以对象形式分发
const {
type,
payload
} = unifyObjectStyle(_type, _payload)
// 建立action对象
const action =