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

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


第一种方法 使用suspense 包裹你的组件 感觉不太好 文档

<template>
 <suspense>
        <router-view></router-view>
</suspense>
</template>

<script>
export default {
  async setup() {
    // 在 `setup` 内部使用 `await` 需要非常小心
    // 因为大多数组合式 API 函数只会在
    // 第一个 `await` 之前工作
    const data = await loadData()

    // 它隐性地包裹在一个 Promise 内
    // 因为函数是 `async` 的
    return {
      // ...
    }
  }
}
</script>

第二种方法 使用生命周期钩子

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,
    };
  },
posted @ 2021-07-08 15:53  阿臻  阅读(18599)  评论(0编辑  收藏  举报