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

vue.jsVuejs2Async Await

vue.js Problem Overview


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?

vue.js Solutions


Solution 1 - vue.js

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;
},

Solution 2 - vue.js

> 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.

Solution 3 - vue.js

Just use $nextTick to call async functions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTaichiView Question on Stackoverflow
Solution 1 - vue.jsEder DíazView Answer on Stackoverflow
Solution 2 - vue.jsHerobrineView Answer on Stackoverflow
Solution 3 - vue.jsNeevorView Answer on Stackoverflow