2.5 KiB
Vuex
In ./store/index.js you can define your state. For simple apps you can leverage this single file. For anything more advanced you should use modules.
https://vuex.vuejs.org/guide/modules.html
state
The state serves as a single source of truth for what you need. You typically have only one store for each application, but you can break it down into modules if needed.
You declare your variables you need in the state. To affect the state, you do mutations and actions.
getters
Getters are like computed propeties for the state. If you needed derived properties of what's in the state - you can define a getter for this purpose. For example, if you have a list in the state you can define a getter that returns the length of that list. This is useful because you might need to do this in more than one Vue component - duplicating code. Using a getter means you can access it from the store.
You can do any function in getters - more complicated actions as properties reduces the amount of duplicated code across components.
mutations
To change the state you need to use a mutation. Each mutation has a string type and a handler. The handler function is where we peform state modifications and it will receive the state as its first argument.
You cannot call a mutation handler directly - think of them like event registration. To call it, you must do a store.commit('handlername').
You can pass a payload to a mutation, write the mutation to take state, and any other arguments you need. Then do a store.commit('handlername', arg1).
actions
An action is a function that you can use to manipulate the state. Since mutations have to be synchronous, you can use an action if you need asynchronous operations.
An action handler receives a context object which exposes the same set of methods/properties on the store instance. So you can use context.commit to commit a mutation or access the state and getters with context.state and context.getters. You can call other actions with context.dispatch.
You can use arugment destructuring to write cleaner code, rather than accepting the entire context object:
actions = {
async login({dispatch, state}, {email, password}){
...
}
Here this handler only needs to do context.dispatch and context.state. The {email, password} will come from the user object we pass as an argument. Inside this handler we can then access any of the state functions we need to do.