相关疑难解决方法(0)

如何使用 Typescript 在 Vue 3.0 setup() 函数中使用 async/await

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

我正在尝试使用打字稿在 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>
Run Code Online (Sandbox Code Playgroud)

随着async setup()组件“HelloWorld”从页面中消失,Firefox 控制台告诉我

"Uncaught (in promise) TypeError: node is null (runtime-dom.esm-bundler.js)"
Run Code Online (Sandbox Code Playgroud)

当我更改async setup()为 时setup(),代码有效,但随后我将无法在 …

async-await typescript vue.js vuejs3 vue-composition-api

8
推荐指数
3
解决办法
8682
查看次数