When does vuex use action and when does state (update or get) be used?

model:

there are two ways:
1.

this.getData().then(data => {
    data;
})

Mode 1 is to save a state in vuex , and in many cases, I first call updateData to make sure that data in state is up-to-date.
method 2 does not need state , but directly obtains data through action getData . This looks easier and doesn"t make any sense.

Apr.13,2022

if it includes asynchronous operation action, use mutation


action to handle asynchronous operation when changing state synchronously. The generation of action can be considered that mutations cannot operate asynchronously.
generally obtains data directly from state. If the data is calculated and processed, it can be obtained from getters.


has not used vue much, but it depends on whether you want to get data in getDate.then or vuex. Even if you get data in then, you still have to update vuex's state, so it's still commit ('update', data); it's better


first recall the role of vuex, which is used as a state manager.
state is defined as the initial state. Vuex can obtain a certain state directly through Vue.$store.state.xxx .
and mutation is the only way in vuex to modify state-action does not change state, but is used for commit state preprocessing and supports asynchronous processing.
this does not mean that mutation does not support asynchronism , after all, the code callback will eventually affect the state. It's just that if you use asynchronism in mutation, there will be problems with state change tracking in devtools, so mutation is just the set of state, while action is built by the developer, and finally you can call set.
you can execute asynchronous code in the component methods after commit, or you can write this part of the code to action for reuse.


the results of the two methods are different.

the second approach is that data invoked asynchronously is not stored in store, which means that data cannot be shared in other components.
if you really don't need to share data, updateData is a stateless function that doesn't need to be put into store; if you want to reuse the function, put it in a js file and use it after other components import.


state is used to obtain data directly
action is used to modify data, and can include asynchronous operations. For example, in action, request the network interface first and then modify state


first recall the role of vuex, which is used as a state manager.

Menu