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,
    };
  },
原文地址:https://www.cnblogs.com/shiazhen/p/14986454.html