Vue Tip: Use Your Composables Synchronously
You should always call your composables synchronously in setup()
hook or <script setup>
. It would be best not to use await
or Promise.all()
when calling your composables. For example, the following code using the setup()
hook is not recommended:
Vue must know the currently active component instance to register lifecycle hooks, watchers, and computed properties. If you call your composables asynchronously, Vue will not be able to determine the current active component instance and cannot register these features.
<script setup>
is the only place to call composables after using await
. After the async operation, the compiler automatically restores the active instance context for you.
Info
Only in <script setup>
you can call your composables after using await
. After the async operation, the compiler automatically restores the active instance context for you.
Recommendation
I suggest you always call your composables synchronously in both setup()
hook and <script setup>
. Sometimes, you can call them in lifecycle hooks like onMounted()
. This will ensure that your composables are always called in the correct context and that Vue can register all the necessary features.
A good example is the useFetch
composable to fetch data from an API:
You can call this composable synchronously in the setup()
hook or <script setup>
:
StackBlitz
Try it yourself in the following StackBlitz project:
Further Reading
Async with Composition API is an excellent article by Anthony Fu that explains this topic in more detail.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Custom SPA Loading Template for Your Nuxt Application
When using the client-side rendering mode, Nuxt will display a loading indicator until the application is hydrated. The loading indicator is a simple spinner. You can customize the loading indicator by creating a custom loading component.
Vue Tip: Event Handling
There are different ways how to handle events in Vue. Let's take a look at them.