What is the best way to ensure elements are rendered in Vue only when they are fully prepared?

Is there a way to delay the rendering of images in my list until all content is ready? I want everything, including text and classes, to finish loading before displaying anything. Even with v-cloak, it's not working!

I'm having difficulty with this particular aspect.

https://i.sstatic.net/fgw5M.png

Even though the entire list is rendered, some images are still pending.

Below is an excerpt of my code:

<div id="app">
    <h2>Todos:</h2>
    <ol>
        <li v-for="todo in todos">
            <img :src="todo.img" width="100px">
            {{todo.name}}
        </li>
    </ol>
</div>

new Vue({
    el: "#app",
    data: {
        todos: []
    },
    created: function(){
        this.requestApi();
    },
    methods: {
        requestApi(){
            this.todos = [
                { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "AAA" },
                { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "BBB" },
                { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "CCC" },
                { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "DDD" }
            ];
        }
    }
})

https://jsfiddle.net/vxy4gnj8/3/

The issue may not be clear in the JSFiddle since it doesn't send a real api request and renders too quickly.

Answer №1

Utilize the v-if directive to display a component only after the requestApi function has completed:

<div id="app">
  <div v-if="!isLoading">
    <h2>Todos:</h2>
    <ol>
        <li v-for="todo in todos">
            <!-- Additional logic may be added here -->
            <img :src="todo.img" width="100px">
            {{todo.name}}
        </li>
    </ol>
  </div>

</div>

new Vue({
  el: "#app",
  data: {
      todos: [],
      isLoading: true
  },
  created: function(){
      this.requestApi();
  },
  methods: {
      requestApi(){
        this.todos = [
          { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "AAA" },
          { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "BBB" },
          { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "CCC" },
          { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "DDD" }
        ];
        this.isLoading = false
      }
  }
})

Keep in mind that the isLoading flag is utilized to determine if the request has been finalized or not.

Answer №2

fetchDataFromApi(){
    const self = this;
    const itemList = [
      { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "AAA" },
      { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "BBB" },
      { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "CCC" },
      { img: "https://steamcdn-a.akamaihd.net/apps/dota2/images/mars/hero_mars93fd33s5.jpg", name: "DDD" }
    ];

    Promise.all(
        itemList.map(item=>new Promise((resolve,reject)=>{
            const image = new Image();
            image.addEventListener("load",function(){
                // in this context, 'this' refers to the image element
                this.__isLoaded__ = true;
                resolve(this);
            },{once:true})
            image.addEventListener("error",function(){
                this.__isLoaded__ = false;
                resolve(this);
            },{once:true});

            image.src = item.img;
        }))
     ).then(imageArr=>{
        const successfulImages = imageArr.filter(image=>image.__isLoaded__);
        console.log(`Process completed. ${imageArr.length} images were loaded. ${successfulImages.length} of them were successfully loaded`);

        self.itemsToDisplay = itemList;
     })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you restrict a textbox input to accept only numerical values and decimals using ng-pattern?

I'm working on a code that needs to accept both decimals and integers. How can I verify this using the ng-pattern? An example of the code: Some test cases include: 1) 22 = Should pass, 2) 22.5 = Should pass, 3) 2a = Should fail, 4) @#@ = Should ...

Using various functions for event listeners

Avoiding jQuery Hello there! I'm currently working on implementing multiple Event Listeners for a button. function logoContame(){ var logo = document.getElementById("logoheader"); logo.addEventListener("click", hideDivHistorias) ...

Having trouble redirecting to the Google login screen with Passport Google Auth 2.0

Greetings, I have encountered an issue with my server setup. I am attempting to redirect users to the Google authentication screen when they navigate to the /auth/google path. However, instead of being redirected, I am consistently landing on my 404 error ...

Is it possible for a Node.js server to specifically generate dynamic HTML, with Nginx handling the distribution of static data, and then automatically deliver the content to the client?

After primarily working with Apache and PHP, I've recently started exploring Nginx and Node.js and have been really enjoying the experience. Initially, I set up an Express server to handle website files and HTML rendering using Handlebars. However, I ...

The backend of Asp.net core 3.1 is unable to retrieve the Identity stored in the cookie

I am encountering an issue with my application that has a vue.js frontend and asp.net core 3.1 backend. The backend utilizes SignInManager and Identity with cookie authentication. Strangely, API requests work perfectly fine when made from Postman, roles ar ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

Trouble accessing HTML file in web browser

I just finished creating a basic webpage called HelloWorld.html using HTML, JavaScript, and CSS. It runs smoothly when I open it from Eclipse IDE and view it through a browser. The functionality of the page is that it contains 5 buttons, each revealing th ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Tips on displaying each element of an array in a unique format within a React component

I am working on creating a component that will display data in boxes. Each set of constant data should be placed within a div for organization. Currently, I have a Box component that is responsible for displaying the data. The Tutorial component receives ...

provide a hyperlink to the icon located in front of the navigation bar

I'm struggling to come up with a suitable title for this issue. What I am trying to achieve is placing a small icon in front of the navbar so that visitors can click on it and be directed to another site. Initially, I attempted to place the icon using ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Guide to Generating Extern for a Constant Variable in Google Closure Compiler (Variable Cannot be Renamed due to Eval)

Currently, I am using Google Closure Compiler in "SIMPLE_OPTIMIZATIONS" mode for my JavaScript code. However, I encountered an issue when the obfuscation changed the variable name from "_u" to "a", resulting in an error that "_u" is not defined in the cons ...

Having difficulty converting an object into an iterable using an arrow function

Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable. The Group class represents a collection of values, akin to a Set, equipped with methods for adding, removing, and che ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

Increase and decrease a counter in Javascript by clicking on two separate image tags, with increments and decrements between 1 and 10

Hello! I really appreciate your help. I am currently facing the following issue: <div id="thumb1"> <img class="img-responsive" id="prova" src="img/thumb-up-dark.png" alt=""> <div id="pinline">0</div> ...

The width values in the array are constantly shifting upon refreshing

Would it be possible to create an array called slide_widths, which will contain the widths of all the .slide elements? $( document ).ready(function() { var $slider = $('.slider ul'); var slider_width = $slider.width(); var $slides = $(&apo ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...

Are you experiencing issues with your Ajax request?

I've been struggling to retrieve json data from an API. Despite my efforts, the GET request seems to be executing successfully and returning the correct data when I check the Net tab in Firebug. Can anyone offer advice on what could be going wrong or ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...