created() {
this.$store.watch(
state => {
return state.httpRequest;
},
(oldVal, newVal) => {
console.log(oldVal, newVal);
}
);
},
不会触发,因为httpRequest
是一个对象。
答案 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)
您可以尝试通过vuex
在computed
部分的mapState
中映射状态以获得所需的值
computed : {
...mapState('yourNameSpace', {
httpRequest : state => state.httpRequest
})
}