Vue Answers

How to wait for data before rendering with Vue.js?

Spread the love

Waiting for data before rendering in Vue.js typically involves utilizing conditional rendering or loading states.

To do this we write:

  <div v-if="dataLoaded">
    <!-- Your content here -->
    {{ data }}
  <div v-else>

export default {
  data() {
    return {
      data: null,
      dataLoaded: false
  mounted() {
    // Simulate an asynchronous data fetch
  methods: {
    fetchData() {
      // Simulate an asynchronous data fetch (e.g., an API call)
      setTimeout(() => {
        // Once data is fetched, update the data property and set dataLoaded to true = "Some data fetched";
        this.dataLoaded = true;
      }, 2000); // Simulating a 2-second delay for demonstration purposes

In this example, we have a dataLoaded boolean flag to indicate whether the data has been loaded.

We use v-if to conditionally render the content based on whether dataLoaded is true.

While the data is being fetched, a loading message is displayed.

Once the data is fetched successfully, dataLoaded is set to true, and the actual content is rendered.

Replace the fetchData() method with your actual data fetching logic, such as making an API call with Axios or Fetch.

Once the data is received, update the data property with the fetched data and set dataLoaded to true.

This will trigger the rendering of your component with the fetched data.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *