How to monitor Vuex data changes in components

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 watchfunction, which can be used to monitor

  • watch(fn: Function, callback: Function, options?: Object): Function

Responsive listens fnreturn value, the callback function when the value changes. fnReceive 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.$watchparameters of the method.

Code

  created () {
    this.$store.watch((state, getters) => {
      return state.count
    }, () => {
      this.changeCount++
    })
  }

Guess you like

Origin blog.csdn.net/weixin_43837268/article/details/109274215