如何观察vuex状态?

时间:2019-09-14 11:15:22

标签: vue.js

当我的vuex状态数据更改时,我需要在组件内触发一个函数,但是它不起作用,关于vuex的监视钩是否有任何错误用法?

const state = {
     currentQueryParameter:[],

 };

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

在组件中

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

1 个答案:

答案 0 :(得分:0)

从技术上讲,您所做的是正确的并且可以正常工作。

但是仍然有几处出问题:

  1. 如果希望状态为反应式,则需要使用本机数组方法(.push(), .splice()等)填充Array。 Vue.set()仅用于设置对象属性。

  2. 您正在观看currentQueryParameter,它是一个数组。它的值不会因您的突变而改变-它保持不变。如果还想观察嵌套的元素,则需要在观察器中使用deep标志,如下所示:

    watch: { '$store.state.currentQueryParameter': { deep: true, handler(newVal) { console.log('queryParameter changed'); } } }

  3. 我不知道您要如何在突变中对此进行处理: Vue.set(info, info.index, info.value);,但您不应更改传递给函数的属性。