Čamo
Čamo

Reputation: 4192

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?

Upvotes: 0

Views: 1547

Answers (1)

RenaudC5
RenaudC5

Reputation: 3839

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>

Upvotes: 1

Related Questions