[英]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.