vue3.0 中 如何在setup中使用async await
第一種方法 使用suspense 包裹你的組件 感覺不太好 文檔
<template>
<suspense>
<router-view></router-view>
</suspense>
</template>
export default {
async setup() {
// 在 `setup` 內部使用 `await` 需要非常小心
// 因為大多數組合式 API 函數只會在
// 第一個 `await` 之前工作
const data = await loadData()
// 它隱性地包裹在一個 Promise 內
// 因為函數是 `async` 的
return {
// ...
}
}
}
第二種方法 使用生命周期鈎子
setup() {
const users = ref([]);
onBeforeMount(async () => {
const res = await axios.get("https://jsonplaceholder.typicode.com/users");
users.value = res.data;
console.log(res);
});
return {
users,
};
},