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?
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.
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.
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.
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.
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; },
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With