【发布时间】:2020-12-12 00:08:07
【问题描述】:
在一个 Vue 组件中,我对来自不同来源的数据有两个异步调用(一个是 HTTP 调用,一个是浏览器缓存调用),我希望让加载器旋转,直到两者都完成。当两者都完成时,可以说组件已加载。
...
data() {
return {
loading: true
}
},
mounted: function() {
this.getData(); // HTTP Async API
this.getOtherData(); // IndexedDB Async API
},
...
我正在尝试找出在两者都返回数据时将加载设置为 false 的正确方法。我目前使用标志的方法看起来很脏,但我不确定它是否是最好的方法。
...
data() {
return {
loading: true,
flagA: false,
flagB: false
}
},
mounted: function() {
this.getData(); // HTTP Async API
this.getOtherData(); // IndexedDB Async API
},
methods: {
getData() {
...
//Once done
this.flagA = true
if (this.flagA == true && this.flagB == true) this.loading = false
},
getOtherData() {
...
//Once done
this.flagB = true
if (this.flagA == true && this.flagB == true) this.loading = false
}
...
有更好的方法吗?
编辑显示非 HTTP 函数:
getOtherData() {
var request = indexedDB.open("Database", 1);
request.onerror = event => {
//IndexedDB is not supported. Resort to fallback option and continue regular program flow
};
request.onsuccess = event => {
this.db = event.target.result;
var transaction = this.db.transaction(["project"], "readwrite");
var projectStore = transaction.objectStore("project");
var projectReq = projectStore.get(1);
projectReq.onsuccess = () => {
this.flagB = true;
};
projectReq.onerror = () => {
//error
};
};
【问题讨论】:
标签: javascript vue.js vuejs2 promise vue-component