vue.js - 如何在大型 SPA 中使用良好的 VueX 商店设计?

标签 vue.js redux vuex state-management

我对 VueJS 比较了解,我也很熟悉 VueX 的使用。我正在从事几个 VueJS 项目,但我正在努力设置我的商店。

我有几个问题:

  • 如何拆分我的模块?每个资源(项目、文章等 等等),还是我的网络应用程序中的每个“页面/容器”?
  • 商店应该包含(并坚持)什么?界面状态或数据,或两者兼而有之?
  • 如何为我的模块、getter、操作和变更使用一个好的命名?

To be sure: I do know the syntax and use of Vue and VueX. My question is focused on the structure / architecture of VueX and its store.

希望你们能用一些术语或好的视频/帖子帮助我解决这个问题!

提前谢谢你,鲍勃

最佳答案

我认为有很多方法可以组织您的应用程序商店,但我大部分时间都是这样做的:

+ store
  - actions.js // global actions (like a for snackbar singleton, loader etc)
  - getters.js // global getters (like a for snackbar singleton, loader etc)
  - index.js // import all other indexes (in the subfolders)
  - mutations.js // global mutations (like a for snackbar singleton, loader etc)
  - state.js // global state (like a for snackbar singleton, loader etc)
  + common
    - actions.js // common actions (shared with all resources)
    - getters.js // common getters (shared with all resources)
    - mutations.js // common mutations (shared with all resources)
    - state.js // common state (shared with all resources)
  + subfolder1 // a resource (like an article, a user, ...)
    - index.js // imports common/* files or siblings overriding it, and exports it
    - actions.js // optional file overriding common/actions.js
    - getters.js // optional file overriding common/getters.js
    - mutations.js // optional file overriding common/mutations.js
    - state.js // optional file overriding common/state.js
  + subfolder2 // an other resource ...
  + ...

common 文件夹中,您拥有“普通”资源的代码库,这有助于避免为每个要处理的资源复制它。如有必要,您可以通过覆盖所需方法的专用文件为特定资源覆盖它。

下面是一个为特定资源覆盖 common/actionos.js 文件的 fetchDB 方法的文件示例:

import { actions as baseActions } from "../common/actions"

const actions = Object.assign({}, baseActions) // we don't want to edit the base instance

// overrides the common method
actions.fetchDb = async function(context, args) {
  args.params.url = "myresource"
  await baseActions.fetchDb.call(this, context, args.params)
}

export default actions

主要优点是它减少了代码重复并保持资源分离,让您有机会在需要时调整它们的行为。

您认为这个组织能满足您的需求吗?

关于vue.js - 如何在大型 SPA 中使用良好的 VueX 商店设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55406998/

相关文章:

javascript - Formik 和 ReactJs : SetFieldValue from child to parent component

reactjs - 在没有反应路由器的情况下以编程方式重定向到 URL

javascript - mapGetters 仅在第一次加载时出现 react 性问题

javascript - 使用 vue.js 和 axios 操作注入(inject)的 HTML

vue.js - 如何绑定(bind)到 Vue JS 中的属性?

javascript - Vuex 观察者错误地触发了两次

html - vue提交按钮数据

javascript - 向 'Failed propType: Invalid prop ` 提供的 React 错误 `Provider` children,需要一个 ReactElement'

javascript - vuex- 状态作为函数或对象文字返回

将可能为空(但不是空)的值传递给匿名回调时, typescript 会提示