How to watch for vuex state?

I need do fire a function within component when my vuex state data change, but it does not work , is there any wrong usage about watch hook for vuex?

const state = {
     currentQueryParameter:[],

 };

 const mutations = {
    currentQueryParameter(state,info){
         state.currentQueryParameter[info.index]=info.value
          Vue.set(info, info.index,   info.value);
}
}

in component

  watch: {
       '$store.state.currentQueryParameter': function() {
        console.log("changed")
        this.getData()
  }
 },

Upvotes: 1

Views: 10004

Answers (1)

MarcRo
MarcRo

Reputation: 2473

What you are doing is technically correct and will work.

However several thing are still going wrong:

  1. If you want your state to be reactive you need to fill Arrays with native array methods (.push(), .splice() etc). Vue.set() is only used to set Object properties.

  2. You are watching currentQueryParameter, which is an Array. Its value does not change through your mutation - it stays the same Array. If you want to watch nested elements as well, you need to use the deep flag in your watcher, like so:

watch: {
  '$store.state.currentQueryParameter': {
    deep: true,
    handler(newVal) {
      console.log('queryParameter changed');
    }
  }
}
  1. I don't know what you are trying to do with this one in your mutation: Vue.set(info, info.index, info.value); but you should not mutate the properties you pass to a function.

Upvotes: 10

Related Questions