简体   繁体   中英

When to use vuex (in Nuxt)?

I'm about to create a Vue.js project (ex. online reminder) and it implemented with RESTful API. I know that Vuex is a state management pattern but i don't know when to use it, because in my idea right now is every time i gonna implement a feature which will call a service will also create a store for that. like example: Authentication Service to be called in the Authentication Store .

My pattern/structure:

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

First question: I am implemented login feature, then created a service login method. so my question is do i really need to create action login method in store?

Second question: In what particular module/feature or in when to use the store Vuex ?

You need to understand which issue Vuex solves: 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 is basically helping you passing data globally without relying on props and emit all day long. And that's pretty much all.


If you have let's say a cart of grosseries, you may put this in Vuex because you can go around all your website and throw some items at it. Relying on local state would be to cumbersome to compute the final checkout.

If you are fetching 10 photos from an API for your homepage, it may not be really useful to have the ability to reach it anywhere in your app, hence overkill to pass it to Vuex. In that case, local state and some props/emit is probably enough.

So, at the end it all depends on how you want to organize your code, try to not get too overkill with it.


For your second question, it's opinion-based and it depends. So, the best is for you to try it out and see how it goes. Would be able to change afterwards if there is an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM