Javascript Vue/Vuex在创建的钩子中等待异步调度
我无法使从firebase获取数据的函数异步: 创建组件时,我有:Javascript Vue/Vuex在创建的钩子中等待异步调度,javascript,vue.js,async-await,vue-component,vuex,Javascript,Vue.js,Async Await,Vue Component,Vuex,我无法使从firebase获取数据的函数异步: 创建组件时,我有: created(){ this.$store.dispatch("fetchSections"); } Vuex行动: actions: { async fetchSections({ commit }) { var sectionsRef = db.collection("sections"); try { await sectionsRef.ge
created(){
this.$store.dispatch("fetchSections");
}
Vuex行动:
actions: {
async fetchSections({ commit }) {
var sectionsRef = db.collection("sections");
try {
await sectionsRef.get().then((querySnapshot) => {
var collect = querySnapshot.docs.map((doc) => doc.data());
commit("addToSections", collect);
});
} catch (error) {
console.log(error.message + " -- " + error.statusText);
}
},
}
问题:在获取数据之前,会创建另一个组件
我也试过:
actions: {
async fetchSections({ commit }) {
var sectionsRef = db.collection("sections");
try {
let allSections = await sectionsRef.get();
for (const doc of allSections.docs) {
var collect = doc.data();
commit("addToSections", collect);
}
} catch (error) {
console.log(error.message + " -- " + error.statusText);
}
},
},
组件的
created
hook不允许延迟渲染,只提供一些代码在组件生命周期的那个时刻运行
使用钩子对数据进行异步调用时,可以使用v-if
防止依赖该数据的子元素出错:
{{item}}
加载。。。
如果没有v-if
,v-for
将尝试访问可能还不存在的someData
,这可能会在访问someData
的属性时引发错误