- 使用watch方法监听Vuex state的变化:
this.$store.watch(
(state) => state.someState,
(newValue, oldValue) => {
console.log('someState changed from', oldValue, 'to', newValue);
}
);
- 使用subscribe方法监听mutation的变化:
store.subscribe((mutation, state) => {
console.log('mutation.type:', mutation.type);
console.log('mutation.payload:', mutation.payload);
});
- mapState / mapGetters和组件的watch结合使用:
如果你想监听Vuex中某个模块的具体状态,可以结合mapState或mapGetters和Vue组件的watch方法,代码更加简洁和模块化
import { mapState } from 'vuex';
export default {
computed: {
...mapState({
someState: state => state.someModule.someState
})
},
watch: {
someState(newValue, oldValue) {
console.log('someState in module someModule changed from', oldValue, 'to', newValue);
}
}
};
- subscribeAction方法监听action的触发:
如果你对action 的触发感兴趣可以使用Vuex提供的subscribeAction方法来监听action的触发
store.subscribeAction((action, state) => {
console.log('action.type:', action.type);
console.log('action.payload:', action.payload);
});
- Custom Plugin:
有时候你需要在Vuex中进行更高级的监听和操作,可以考虑编写一个自定义的Vuex插件
const myPlugin = store => {
store.subscribe((mutation, state) => {
console.log(`Mutation type: ${mutation.type}`);
console.log(`Mutation payload: ${mutation.payload}`);
console.log(`Current state: `, state);
});
};
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
plugins: [myPlugin]
});
store.commit('increment');