如何查看vuex商店中的深层(嵌套)更改?

时间:2019-08-19 14:14:02

标签: vue.js vuex

  created() {
    this.$store.watch(
      state => {
        return state.httpRequest;
      },
      (oldVal, newVal) => {
        console.log(oldVal, newVal);
      }
    );
  },

不会触发,因为httpRequest是一个对象。

2 个答案:

答案 0 :(得分:1)

您可以将{ deep: true }作为第三个参数:

created() {
  this.$store.watch(
    state => {
      return state.httpRequest;
    },
    (oldVal, newVal) => {
      console.log(oldVal, newVal);
    },
    { deep: true }
  );
}

Here's the documentation for the watch method.

这是一个简单的例子:

Vue.config.productionTip = false;
Vue.config.devtools = false;

const store = new Vuex.Store({
  state: { httpRequest: null },
  mutations: {
  	changeRequest(state) {
    	if (!state.httpRequest) {
        state.httpRequest = { foo: 1 };
      } else {
        state.httpRequest.foo++;
      }
    }
  }
});

new Vue({
	el: '#app',
  store,
  methods: {
    onClick() {
      this.$store.commit('changeRequest')
    }
  },
  created() {
    this.$store.watch(
      state => {
        return state.httpRequest;
      },
      (oldVal, newVal) => {
        console.log(oldVal, newVal);
      },
      { deep: true }
    );
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="onClick">
    Click
  </button>
</div>

答案 1 :(得分:1)

您可以尝试通过vuexcomputed部分的mapState中映射状态以获得所需的值

computed : {
   ...mapState('yourNameSpace', {
      httpRequest : state => state.httpRequest
   })
}