我有一个相当简单的Vue
组件(去除了不必要的部分):
Vue.component('equipment-tree', {
data(){
return {
tree: [],
}
},
template: `
<template>
<div id="equipment_tree"></div>
</template>`,
mounted: function(){
this.getTreeView()
console.log('4. TREE LOADED AND VISIBLE');;
},
methods: {
setUpTree(){
$("#equipment_tree").jstree("destroy");
$('#equipment_tree').jstree({
core : {
data : this.tree,
multiple: false,
themes: {
dots: true
}
},
});
console.log("2. TREE SET UP")
},
getTreeView(){
fetch("myurl /*just a URL */",
{
method: 'GET',
})
.then((response) => response.json())
.then((data) => {
console.log('1. GOT DATA');
this.tree = JSON.parse(data.tree);
this.setUpTree();
console.log('3. SET UP COMPLETE');
})
}
}
})
在挂载时,我调用getTreeView()
方法从数据库获取数据,将其保存在变量tree
中,然后调用setUpTree()
方法,使用jstree
库创建树形结构。当我在日志中运行它时,看到:
4. TREE LOADED AND VISIBLE
1. GOT DATA
2. TREE SET UP
3. SET UP COMPLETE
也就是说,在调用 getTreeView()
之后,流程仍在继续。那么,如果我想等待 getTreeView()
执行完毕,使日志 4. TREE LOADED AND VISIBLE
最后被真正打印出来,该怎么办呢?
我尝试使用 async/await
,如下所示:
mounted: function(){
this.getTreeView()
console.log('4. TREE LOADED AND VISIBLE');;
}
转换为
mounted: async function(){
await Promise.resolve(this.getTreeView());
console.log('4. TREE LOADED AND VISIBLE');
}
但我得到了与之前相同的结果。如果按照这个问题的答案,情况也是一样的。
我该如何等待方法getTreeView()
执行完毕?请注意,这只是一个简化的示例,因为我想了解它的工作原理,而不仅仅是日志的顺序。