如何解决我如何使用Typescript在Vue 3.0 setup函数中使用async / await
(此问题已针对JavaScript回答,请参见下文,但此问题特定于TypeScript,其行为有所不同)
我正在尝试使用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()
时,代码起作用了,
但后来我将无法在设置功能内使用async / await。
所以我的问题是: 如何使用Typescript在setup()函数中使用async / await?
编辑:
此问题的答案:why i got blank when use async setup() in Vue3表明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
和 created
生命周期钩子周围运行,在 beforeMount
和 {{ 1}}:
mounted
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。