Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
Taichi Avatar asked Nov 28 '18 06:11

Taichi


People also ask

Is async await available in ES6?

Async and Await both are considered as special keywords which are provided by ES6 in order to perform some asynchronous data operations. Even synchronous operations could also be performed using these keywords.

How do I use async and await in Vue?

You can use async and await for your lifecycle hooks, methods and watcher functions. One exception here is computed properties, which don't allow the use of async and await . In order to use await in the methods of you Vue component you prefix the method name with the async keyword.

What is difference between created and mounted Vuejs?

As such, any DOM manipulation, or even getting the DOM structure using methods like querySelector will not be available in created() . As mentioned in the article on lifecycle hooks, created() is great for calling APIs, while mounted() is great for doing anything after the DOM elements have completely loaded.

What does mounted do in Vue?

The mounted() hook is the most commonly used lifecycle hook in Vue. Vue calls the mounted() hook when your component is added to the DOM. It is most often used to send an HTTP request to fetch data that the component will then render.


1 Answers

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; }, 
like image 120
Eder Díaz Avatar answered Sep 23 '22 11:09

Eder Díaz