Did you know that Vue3 Components Can “Pause” Rendering?

Shawn King
7 min readSep 10, 2024

Introduction

Sometimes we want to render a component only after fetching data from the server. Here are some methods to achieve this:

  1. Request data in the parent component and use v-if to render the child component only after receiving the data, passing it via props.
  2. Request data in the onMounted lifecycle of the child component and use v-if in the template to control rendering.

Both methods have drawbacks. The ideal solution is to handle data fetching inside the child component and “pause” rendering until the data is ready.

Example

Data Request in Parent Component

Father:

<template>
<Child v-if="user" :user="user" />
<div v-else>
<p>loading...</p>
</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import Child from "./Child.vue";
const user = ref(null);
async function fetchUser() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "John",
phone: "xxxxxxxxxx",
});
}, 2000);
});
}
onMounted(async () => {
user.value = await fetchUser();
});
</script>

Child:

<template>
<div>…

--

--

Shawn King
Shawn King

Written by Shawn King

Focusing on front-end development and internet writing. Sharing technical tutorials and original fiction. https://skstory.online/