Describes how to monitor the state in the vuex component.
Preface
I wonder if you have ever encountered such a situation? The state in vuex is used in a group, and the state Initialization is completed through asynchronous loading. The state obtained by the component during rendering is null. That is to say, the component has completed rendering before the asynchronous completion, resulting in the component data not being rendered in time.
Example
Example:
// Topo. vuecreated () {this. getUserAndSysIcons () ;}, methods: {getUserAndSysIcons () {const self = this; // user icon iconApi. getUserIcons (). then (response => {self. $ store. dispatch ('setusericons', response. data );});}}
Call getUserAndSysIcons () to asynchronously initialize userIcons when created or mounted is completed in topo. vue to facilitate the use of this data in other components.
// Modifyhost. vuemounted () {this. userIcons = this. $ store. state. topo. userIcons; // user icon}
To render data in modifyhost. vue, use userIcons. When the modifyhost. vue component mounted is complete, the userIcons data has not been initialized. The modifyhost. vue rendering is empty.
Thoughts
If the asynchronous acquisition of userIcons in topo. vue is complete, initialize userIcons in the modifyhost. vue component. In this way, the rendering is automatically changed. So how can we know when Asynchronization will be completed?
So I thought of vue A Good Thing, watch monitoring, and listen to some data changes. We all know that it is easy to monitor the changes of local data in components. So how can we monitor the changes in the state? Therefore, the computed computing attribute is used. The procedure is as follows:
Solution
Write a computing attribute getUserIcons in computed and return to userIcons in status management. Then, listen to the changes in the computing attribute in watch and assign a value to userIcons in modifyhost. vue.
computed: { getUserIcons() { return this.$store.state.topo.userIcons; }},watch: { getUserIcons(val) { this.userIcons = val; }}
Final Effect
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.