Analysis: This question examines the application of Vuex and the mechanism of monitoring data changes within Vue
解答
: First determine what problem does Vuex appear to solve? Vuex is a framework that appears to solve state sharing between components.There are several elements that constitute the key to Vuex, state (state) mutations actions,
state represents the state data that needs to be shared
Mutations means that the set of methods to change the state can only be synchronous updates and cannot write asynchronous requests such as ajax
Actions If you need to make an asynchronous request, you can initiate it in actions and submit it to mutations for synchronous updates.
That is, state is responsible for managing state, mutation is responsible for synchronously updating state, action is responsible for obtaining data asynchronously and submitting it to mutation
So the component monitoring Vuex data changes is to monitor the state changes in Vuex.
第一种方案
We can do this in the component through the component's watch method , because the component can map the state data to the component's calculated properties,
Then monitor the calculated properties of the mapping and the code is as follows
// State data in vuex state: { count: 0 }, // Map state data in component A to the calculated attribute computed: { // this.$store.state.count // mapState turns the global count into direct use Data ... mapState(['count']) } // A component monitors the changes of count calculation properties watch: { // watch can monitor data data or global vuex data count () { // use its own data Count this.changeCount++ } }
第二种方案
The store object in vuex itself provides a watch
function, which can be used to monitor
-
watch(fn: Function, callback: Function, options?: Object): Function
Responsive listens fn
return value, the callback function when the value changes. fn
Receive the state of the store as the first parameter and its getter as the second parameter. Last received parameter indicates an optional object of Vue vm.$watch
parameters of the method.
Code
created () { this.$store.watch((state, getters) => { return state.count }, () => { this.changeCount++ }) }