简体   繁体   English

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

[英]How can I use async/await in the Vue 3.0 setup() function using Typescript

(This question has been answered for JavaScript, see below, but this question is specific for TypeScript, which behaves differently) (此问题已针对 JavaScript 回答,见下文,但此问题特定于 TypeScript,其行为不同)

I'm trying to use async functionality in Vue3.0 using typescript.我正在尝试使用打字稿在 Vue3.0 中使用异步功能。

Without async this code works nice:没有异步,这段代码很好用:

// 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>

With async setup() the component "HelloWorld" disappears from the page, and the Firefox console tells me使用async setup()组件“HelloWorld”从页面中消失,Firefox 控制台告诉我

"Uncaught (in promise) TypeError: node is null (runtime-dom.esm-bundler.js)"

When I change async setup() to setup() , the code works, but then I would not be able to use async/await inside the setup function.当我将async setup()更改为setup() ,代码可以工作,但是我将无法在 setup 函数中使用 async/await 。

So my question: how do I use async/await inside the setup() function using Typescript?所以我的问题是:如何使用 Typescript 在 setup() 函数中使用 async/await?

EDIT:编辑:

The answer to this question: why i got blank when use async setup() in Vue3 shows that async setup() does work with JavaScript, so I would expect it to work in TypeScript as well.这个问题的答案: 为什么在 Vue3使用 async setup() 时我得到空白表明async setup()确实适用于 JavaScript,所以我希望它也适用于 TypeScript。

Try to use onMounted hook to manipulate asynchronous call :尝试使用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 现场演示

Another way of doing this:这样做的另一种方法:

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

 return {
   users,
 }

And you don't have to wait for it to mount, this is similar to using created() with the options API.而且您不必等待它挂载,这类似于将 created() 与 options API 一起使用。

An alternative is to use the promise chain, the benefit of doing this is that the code is run even before the beforeCreate lifecycle hook:另一种方法是使用 promise 链,这样做的好处是代码甚至在beforeCreate生命周期钩子之前运行:

import { defineComponent, ref } from 'vue'
import axios from 'axios'

export default defineComponent({
  setup() {
    const users = ref([])

    axios
      .get('https://jsonplaceholder.typicode.com/users')
      .then(({ data }) => (users.value = data))

    return {
      users,
    }
  },
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM