不知道大家有没有遇到过这样一种情况? vuex中的state会在某一个组建中使用,而这个状态的初始化是通过异步加载完成的。组件在渲染过程中,获取的state状态为空。也就是说组件在异步完成之前就已经完成渲染了,导致组件的数据没有来得及渲染。
问题举例
举例说明如下:
// topo.vue
created() {
this.getUserAndSysIcons();
},
methods: {
getUserAndSysIcons() {
const self = this;
// 用户图标
iconApi.getUserIcons().then(response => {
self.$store.dispatch('setUserIcons', response.data);
});
}
}
在topo.vue中created或者mounted完成的时候调用 getUserAndSysIcons() 异步初始化userIcons,方便在其他组件中使用这个数据。
// modifyhost.vue
mounted() {
this.userIcons = this.$store.state.topo.userIcons; // 用户图标
}
在modifyhost.vue中渲染数据是,需要使用userIcons。在modifyhost.vue组件mounted完成的时候,userIcons数据还没有被初始化。导致modifyhost.vue渲染为空。
在computed中写一个计算属性getUserIcons,返回状态管理中的userIcons。然后在watch中监听这个计算属性的变化,对modifyhost.vue中的userIcons重新赋值。
computed: {
getUserIcons() {
return this.$store.state.topo.userIcons;
}
},
watch: {
getUserIcons(val) {
this.userIcons = val;
}
}