Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them:. If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared helper and import it in multiple places - both are less than ideal.
Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. As of Vue 3.0, the getter's result is not cached as the computed property does.
This is a known issue that requires Vue 3.1 to be released. You can learn more at PR #1878. Getters will receive the state as their 1st argument:.
The getters will be exposed on the store.getters object, and you access values as properties:.
Getters will also receive other getters as the 2nd argument:.
We can now easily make use of it inside any component:.
Note that getters accessed as properties are cached as part of Vue's reactivity system. You can also pass arguments to getters by returning a function.
This is particularly useful when you want to query an array in the store:. Note that getters accessed via methods will run each time you call them, and the result is not cached.
The mapGetters helper simply maps store getters to local computed properties:.
If you want to map a getter to a different name, use an object:.
When you are working with data in your Vuex store, you will often need to update it using a form.
Vuex holds everything in state so that you can display it in multiple areas of your application while keeping things in sync. Let’s look at an example of updating a user's name.
To update the user's name, the standard approach is to dispatch an action. The action will commit a mutation to update the state.
You can’t update state directly, it needs to be handled via a mutation.
To access the state, we can use a getter to fetch the current user’s name. To have that name update in the Vuex store we then need to use a setter which will dispatch an action.
Here we have a basic auth Vuex state:.
To update the authenticated user’s name we add the following computed property in our Vue template. This works by binding to the input field using v-model for the name property.