Vue 3 is coming with a some exciting new features. Composition API is the hottest one at the moment but there are others that excite me as much as it.

One of those new features is called Suspense and it really excites me about the benefits it brings. You might have heard about it already but I will try to show some examples of the usage of Suspense and where it can be beneficial.

What is Suspense?

Suspense is a state of mental uncertainty, anxiety, of being undecided, or of being doubtful. In a dramatic work, suspense is the anticipation of the outcome of a plot or of the solution to an uncertainty, puzzle, or mystery, particularly as it affects a character for whom one has sympathy.

Wikipedia

Back to Vue, Suspense is a component, that you don’t need to import or do any kind of setup, with two <slot> that allows you to render a #fallback while the main component you want to load is not ready.

Ok, it seems vague. I will try to give you an example of how it is used. I also recommend you to take a look into its test cases, especially the first one to get familiar with it.

<Suspense>
  <template #default>
    <!-- The component I want to render -->
  </template>
  <template #fallback>
    <!-- Fallback component shown while my component is not ready -->
  </template>
</Suspense>

That is the basic blueprint of it and it tackles a really common use case: the v-if loading condition.

I consider it the first benefit of Suspense, as now we’ve some standard way of dealing with this scenario. Before Suspense each developer could choose the way they want to implement it, they still can, and it was kind of a nightmare in situations where multiple components were loaded, so you would have loadingHeaderloadingFooterloadingMain, and so on.

At the beginning I wrote “while the main component you want to load is not ready”, what it means is that the main component has some kind of async work, which plays nicely with an async setup() from the new Composition API.

Let’s say we have the following component with some async work to be done in setup:

<template>
  <h1>Ive some async work to do before I can render</h1>
</template>

<script>
export default {
  name: 'MyAsyncComponent',
  async setup() {
    await someAsyncWork();
  }
 }
 </script>

Now we want to use this component somewhere but we want to have a proper loading while it is not ready.

#vue #vue 3 #programming

Go async in Vue 3 with Suspense
13.40 GEEK