什么时候使用 vuex(在 Nuxt 中)?

When to use vuex (in Nuxt)?

我要创建一个 Vue.js 项目(例如在线提醒),它是用 RESTful API 实现的。我知道 Vuex 是一种状态管理模式,但我不知道何时使用它,因为在我的想法中,每次我要实现一个将调用服务的功能时,也会为此创建一个商店。例如:AuthenticationAuthentication Store.

中调用的服务

我的pattern/structure:

 - Service : Call api
 - Store : Call Service
 - Component : Store (Dispatch action)

第一个问题: 我实现了登录功能,然后创建了一个服务登录方法。所以我的问题是我真的需要在商店中创建操作登录方法吗?

第二个问题: 在什么情况下 module/feature 或何时使用商店 Vuex?

你需要了解 Vuex 解决了哪些问题:https://vuex.vuejs.org/#what-is-a-state-management-pattern

Multiple views may depend on the same piece of state. Actions from different views may need to mutate the same piece of state. For problem one, passing props can be tedious for deeply nested components, and simply doesn't work for sibling components. For problem two, we often find ourselves resorting to solutions such as reaching for direct parent/child instance references or trying to mutate and synchronize multiple copies of the state via events. Both of these patterns are brittle and quickly lead to unmaintainable code.

So why don't we extract the shared state out of the components, and manage it in a global singleton? With this, our component tree becomes a big "view", and any component can access the state or trigger actions, no matter where they are in the tree!

Vuex 基本上可以帮助您在全球范围内传递数据,而无需整天依赖 propsemit。这就是全部。


如果你有一车杂货店,你可以把它放在 Vuex 中,因为你可以遍历你的所有网站并向它扔一些东西。依靠本地状态计算最终结帐会很麻烦。

如果您要从主页的 API 中获取 10 张照片,那么在您的应用程序中的任何地方访问它可能并没有多大用处,因此将它传递给 Vuex 就有点过分了。在那种情况下,本地状态和一些 props/emit 可能就足够了。

所以,最后这一切都取决于你想如何组织你的代码,尽量不要太过分。


对于你的第二个问题,它是基于意见的,视情况而定。所以,最好的办法是让您尝试一下,看看效果如何。以后有问题可以改。