如何在Vue 3.0 Setup()函数中使用使用TypeScrip的异步/等待

人气:808 发布:2022-10-16 标签: async-await typescript vue.js vuejs3 vue-composition-api

问题描述

(此问题已针对JavaScript回答,见下文,但此问题特定于TypeScrip,其行为有所不同)

我正在尝试使用TypeScrip使用Vue3.0中的异步功能。

在不使用异步的情况下,此代码运行良好:

// file: components/HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue'

export default defineComponent({
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  async setup() { // <-- this works without 'async'
    const test = 'test'

    // await doSomethingAsynchronous()

    return {
      test,
    }
  },
})
</script>

使用async setup()时,组件&HelloWorld";将从页面中消失,并且Firefox控制台告诉我

"Uncaught (in promise) TypeError: node is null (runtime-dom.esm-bundler.js)"
当我将async setup()更改为setup()时,代码工作, 但这样我就不能在Setup函数中使用Async/AWait。

所以我的问题: 如何在setUp()函数中使用TypeScrip中的异步/等待?

编辑:

此问题的答案:why i got blank when use async setup() in Vue3显示async setup()确实适用于JavaScript,因此我希望它也适用于TypeScrip。

推荐答案

尝试使用onMounted挂钩操作异步调用:

 setup() {
    const users = ref([]);
    onMounted(async () => {
      const res = await axios.get("https://jsonplaceholder.typicode.com/users");
      users.value = res.data;
      console.log(res);
    });

    return {
      users,
    };
  },

LIVE DEMO

143