Is `async/await` available in Vue.js `mounted`?

I'd like to do something like this in mounted() {}:

await fetchData1();
await fetchData2UsingData1();
doSomethingUsingData1And2();

So I wonder if this works:

async mounted() {
    await fetchData1();
    await fetchData2UsingData1();
    doSomethingUsingData1And2();
},

In my environment it raises no errors, and seems to work well. But in this issue, async/await in lifecycle hooks is not implemented.

https://github.com/vuejs/vue/issues/7209

I could not find further information, but is it available in fact?


It will work because the mounted hook gets called after the component was already mounted, in other words it won't wait for the promises to solve before rendering. The only thing is that you will have an "empty" component until the promises solve.

If what you need is the component to not be rendered until data is ready, you'll need a flag in your data that works along with a v-if to render the component when everything is ready:

// in your template
<div v-if="dataReady">
    // your html code
</div>


// inside your script 
data () {
    return {
        dataReady: false,
        // other data
    }
},

async mounted() {
    await fetchData1();
    await fetchData2UsingData1();
    doSomethingUsingData1And2();
    this.dataReady = true;
},

Edit: As stated in the documentation, this is an experimental feature and should not be used in production applications for now.

The correct way to do this in vue3 would be to make your setup() function async like this:

<script>
// MyComponent.vue
export default defineComponent({
/* ... */
    async setup() {
        await fetchData1();
        await fetchData2UsingData1();
        doSomethingUsingData1And2();
        this.dataReady = true;
    }
}
</script>

And then use a suspense component in the parent to add a fallback like this:

<template>
    <Suspense>
        <template #default>
            <MyComponent />
        </template>
        <template #fallback>
            Loading...
        </template>
    </Suspense>
</template>

So you would see the #fallback template while the component is loading, and then the component itself when it's ready.