【发布时间】:2021-02-07 17:25:25
【问题描述】:
我在Vuex 中存储了一个userProfile,以便能够在我的整个项目中访问它。但是如果我想在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 来解决这个问题,但没有任何效果。
【问题讨论】:
标签: javascript vue.js vuejs2 async-await vuex