'How to watch nested Vuex store values
I have a Vue project where I need to watch some Vuex store values. Here is the code:
computed: {
serverCategories: {
get() {
return this.$store.state[this.storeName].serverFilters.categories[0].value.name;
},
set(value) {
return value;
},
}
},
watch: {
serverCategories: {
deep: true,
handler(newVal, OldVal) {
console.log(newVal);
}
}
},
But it does not react on changes. serverCategories still contains the same value although the value in store state is changed. What is wrong with this code?
Solution 1:[1]
You can use the vuex mapGetters which you can wrap in your computed properties (see documentation here)
I would highly recommand using getters each time you need to access the store instead of $store.state.myStore.myValue.
You can also use vuex to mutate your data (through mutations and the vuex function mapMutations or though actions using mapActions)
Example :
store
getters: {
myValue: (state) => state.myValue
}
Vue component
<template>
<p> {{ myValueFromGetter }}</p>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
myValueFromGetter: 'myGetter/myValue'
}
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RenaudC5 |
