【发布时间】:2021-02-26 21:00:50
【问题描述】:
正如 Vuex 文档所说,当项目开始增长时,我们需要一种方法将状态管理分离到一个更加自包含和模块化的可扩展解决方案中。命名空间在这里提供帮助。遗憾的是,在编写 Vuex 模块部分时,缺少如何有效使用它们的信息和示例。
这是我的店铺结构
store
|- modules
|- core
|- country.js
|- region.js
|- ...
|- roullout
|- site.js
|- index.js
这里模块注册index.js
import Vuex from 'vuex'
// Core modules
import coreCountry from "@/store/modules/core/country";
import coreRegion from "@/store/modules/core/region";
// Rollout modules
import rolloutSite from "@/store/modules/rollout/site";
export default new Vuex.Store({
modules: {
// Core modules
core: {
country: coreCountry,
region: coreRegion,
},
// Rollout modules
rollout: {
site: rolloutSite
}
}
})
现在我尝试在某些组件中定义动作
methods: {
...mapActions('rollout/site', [
LIST_REQUEST
])
}
这里的第一个错误:rollout/site is not found 因为我猜rollout 是一个文件夹而不是一个模块,因此site 是一个模块而不是rollout 的嵌套模块。
Vuex 文档 show 如何使用 helper 绑定嵌套模块中的内容,但没有显示带有嵌套模块的商店的架构。
LIST_REQUEST 是一个动作,来自 types.js,定义为:
export const LIST_REQUEST = "rollout/site/LIST_REQUEST";
所以在 site.js 模块中我可以用作:
const actions = {
[types.LIST_REQUEST]: async ({ commit }, payload= {}) => {
// your actions here...
},
}
由于我使用的是 mapActions(),而不是像这样的调度操作:this.$store.dispatch() 我可以直接执行this.LIST_REQUEST()
import {
LIST_REQUEST
} from "@/store/types/rollout/site";
export default {
name: "SiteList",
created() {
this.LIST_REQUEST()
},
methods: {
...mapActions('rollout/site', [
LIST_REQUEST
])
}
}
这里还有一个错误:LIST_REQUEST() 不是函数。出现此错误是因为 mapAction 仍然需要将操作转换为函数
如何使用嵌套模块解决这些问题并使用 index.js。可能我脑子里有点乱,能不能帮我把这些概念说清楚?
【问题讨论】:
标签: vue.js vuex vuex-modules