[英]How can I run a top level async / await function with TypeScript?
[英]How can I use async/await in the Vue 3.0 setup() function using Typescript
(此问题已针对 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>
使用async setup()
组件“HelloWorld”从页面中消失,Firefox 控制台告诉我
"Uncaught (in promise) TypeError: node is null (runtime-dom.esm-bundler.js)"
当我将async setup()
更改为setup()
,代码可以工作,但是我将无法在 setup 函数中使用 async/await 。
所以我的问题是:如何使用 Typescript 在 setup() 函数中使用 async/await?
编辑:
这个问题的答案: 为什么在 Vue3中使用 async setup() 时我得到空白表明async setup()
确实适用于 JavaScript,所以我希望它也适用于 TypeScript。
尝试使用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,
};
},
这样做的另一种方法:
setup() {
const users = ref([]);
(async () => {
const res = await axios.get("https://jsonplaceholder.typicode.com/users");
users.value = res.data;
console.log(res);
})()
return {
users,
}
而且您不必等待它挂载,这类似于将 created() 与 options API 一起使用。
另一种方法是使用 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.