(This question has been answered for JavaScript, see below, but this question is specific for TypeScript, which behaves differently)
I'm trying to use async functionality in Vue3.0 using typescript.
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
"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.
So my question: how do I use async/await inside the setup() function using Typescript?
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.
Try to use
onMounted
hook to manipulate asynchronous call :LIVE DEMO
According to official docs the Best approach is to use
async setup
in child component and wrap that component bySuspense
component in the parent one :UserList.vue
Parent component: