Did you know that Vue3 Components Can “Pause” Rendering?
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:
- Request data in the parent component and use
v-if
to render the child component only after receiving the data, passing it via props. - Request data in the
onMounted
lifecycle of the child component and usev-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>…