If here is my store.js file:
const state = {
count: 0,
loggedIn: false
}
const mutations = {
UP_COUNT(state) {
state++;
}
}
const actions = {
upCount({ commit }) {
commit('UP_COUNT');
}
}
Let's say to increase state count
from one of my Vue components, I will call an action which then commits a mutation:
this.$store.dispatch('upCount');
Then let's say in another Vue component, I want to use the state count:
<div class="count">{{ this.$store.state.count }}</div>
What is wrong with this style? (vs using $this.store.getters
...)
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.
Vuex getter is not reactive.
Mutations: In Vuex state isn't immutable because Vuex provides designated functions called mutations for modifying state without entirely replacing it.
The second key defined in the store is the mutations key. As the name suggests, it contain an object of all of the properties responsible for making changes to the state .
As I pointed out on this post there is no hard and fast way you must do things but following a practice and going with it is best.
Using getters might seem over-kill but you can change the data behind the scenes using getters as long as the getter name remains the same and this saves a lot of work re-factoring and trying to find all the references to other places where you might have used this.$store.state.module.someValue
.
It also allows you to return data based on mutiple state variables into one getter i.e
`isAllowed: 'getIsAllowed'`
could be based on
getIsAllowed (state) {
return state.loggedIn && state.hasPermission && state.somethingElse
}
You can change what isAllowed
is based on easily in one place rather than using each state variable in your components and doing the logic multiple times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With