vue.jsvuejs2async-await

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?


Solution

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