vue3.0 中 如何在setup中使用async await


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,
    };
  },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM