我已经存储了一个userProfileinVuex以便能够在我的整个项目中访问它。但是如果我想在created()钩子中使用它,配置文件还没有加载。该对象存在,但其中没有存储数据。至少在页面的初始加载时。如果我稍后访问它(例如通过单击按钮),一切都会完美运行。有没有办法等待数据完成加载?
以下是如何userProfile设置Vuex:
mutations: {
setUserProfile(state, val){
state.userProfile = val
}
},
actions: {
async fetchUserProfile({ commit }, user) {
// fetch user profile
const userProfile = await fb.teachersCollection.doc(user.uid).get()
// set user profile in state
commit('setUserProfile', userProfile.data())
},
}
这是我要访问它的代码:
<template>
<div>
<h1>Test</h1>
{{userProfile.firstname}}
{{institute}}
</div>
</template>
<script>
import {mapState} from 'vuex';
export default {
data() {
return {
institute: "",
}
},
computed: {
...mapState(['userProfile']),
},
created(){
this.getInstitute();
},
methods: {
async getInstitute() {
console.log(this.userProfile); //is here still empty at initial page load
const institueDoc = await this.userProfile.institute.get();
if (institueDoc.exists) {
this.institute = institueDoc.name;
} else {
console.log('dosnt exists')
}
}
}
}
</script>
通过登录控制台,我发现问题出在代码运行的顺序上。首先,运行该方法getInstitute,然后action运行mutation. 我试图添加一个loaded参数并尝试await解决这个问题,但没有任何效果。