What could be causing the issue of loading text not appearing in Vue.js?

I have the following code snippet in my application:

<div id="app">
  <button v-if="!isPrepared && !isLoading" @click="startLoading()">Start Loading</button>
  <div v-if="isLoading">Loading content...</div>
  <template v-else>
    <img v-show="isPrepared" ref="image" />
  </template>
</div>

<script>
new Vue({
  el: "#app",
  data() {
    return {
      isLoading: false,
      isPrepared: false,
    }
  },
  mounted() {
     
  },
  methods: {
    startLoading() {
      this.isLoading = true;    
      
      for (let i = 1; i < 1E9; ++i) {
         //Simulated loading process;
         const a = 1;
        }
      this.isLoading = false;   
      this.isPrepared = true; 
        
      this.$refs.image.src = 'https://cdn.pixabay.com/photo/2018/07/04/11/58/xiamen-3515964__340.jpg';
    }
  },
})
</script>

When clicking on the "Start Loading" button in this code, the message "Loading..." should briefly display before the image appears. However, there seems to be an issue as the loading message does not appear. Can you identify what's causing this and suggest a fix? It's important to maintain the simulated load for user experience purposes.

Answer №1

If you need the code to pause and wait for a loop to finish, consider making startLoading an async function so that you can use await within it. Make sure to use await on any promises your loop is waiting for. Here's a simple example:

methods: {
  async startLoading() {
    this.isLoading = true;    

    for (let i = 1; i < 1E9; ++i) {
      const a = await // insert your promise here;
      // perform actions with `a`
    }
    this.isLoading = false;   
    this.isLoaded = true; 

    this.$refs.img.src = 'https://cdn.pixabay.com/photo/2018/07/04/11/58/xiamen-3515964__340.jpg';
  }
}

For more information and examples, check out the documentation here.

Answer №2

To implement the functionality, you can utilize the events onload and onerror:

<template>
  <div>
    <!-- button -->
   <button v-if="!isLoaded && !isLoading" @click="startLoading">Begin Loading</button>
    <!-- while loading -->
    <div v-show="isLoading && !isLoaded"&g;t;Loading......</div>
    <!-- display image when loaded -->
    <img 
      :src="imgSrc" 
      v-show="isLoaded" 
      @load="imgLoadedHandler"
      @error="imgFailedHandler" />
  </div>
</template>
<script>
export default {
  data() {
    return {
    imgSrc: '',
      isLoading: false,
      isLoaded: false,
    }
  },
  methods: {
    startLoading() {
      this.isLoading = true;
      this.imgSrc = '...';
    },
    // executed after image loads
    imgLoadedHandler() {
      this.isLoaded = true;
      this.isLoading = false;
    },
    // executed if image fails to load
    imgFailedHandler() {
      this.isLoaded = true;
      this.isLoading = false;     
    }
  }
}
</script>
        

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

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...

How can JavaScript be integrated with Django static URLs?

I have a Django application where I store static images on Digital Ocean Spaces. Displaying these static images in my template is simple:<img>{% static 'images/my_image.png' %}</img> When I inspect the HTML page after loading, I see ...

Is there a way to enable my progressBar to be draggable so that when clicked, it adjusts to a new currentTime position

I am trying to create a seekable audio progress bar in React, but I am facing issues with the seek function not working as intended. Below is my main play buttons file where all the code related to the progress bar is located. import React, { Component } ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) There seems to be an issue ...

How can we determine if a Node.js application will remain operational?

How is the longevity of a Node.js app determined? For example, consider this code snippet: console.log('Hello World'); In this case, the phrase will be printed and the app will exit immediately. However, with a web server that is actively lis ...

Encountered difficulties logging in with MongoDB and Node.js

I encountered an issue while attempting to authenticate a user using MongoDB and Node.js. Although no errors are thrown, the system fails to provide the expected data after the user logs in. Below is a breakdown of my code. server.js var port=8888; va ...

Guide on incorporating parent properties into nested routes?

Is it possible to avoid duplicating the meta properties within a nested route? { path: "/dashboard/users", component: UserIndex, meta: { layout: "UserLayout", title: "User Dashboard", middleware ...

What is the best way to properly pass parameters?

const root = { user: (id) => { console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id))) return storage.select("users", id.id) } } Struggling to correctly pass the parameter ...

Tips for accessing the selected button in notification.confirm() within a PhoneGap app

Recently, I implemented the Phonegap notification.confirm in this way: navigator.notification.confirm( 'Do you wish to proceed?', function() { console.log("Function Called"); }, 'Game Over', 'Continu ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Omit the readme.md file from Vuepress

Currently, I am attempting to remove the README.md from Vuepress in order to utilize it for Github documentation. Instead, I have set up index.md as my homepage. Is there a method to accomplish this task successfully? I experimented with the following ap ...

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

"Learn how to position a div element below the header div and above the footer div while maintaining full height in

Recently delving into the world of reactjs, I find myself facing a challenge with a page that contains 3 distinct blocks formed by divs. Have a look at the layout on my page: My Page This is the code snippet I have worked on: return ( <div> ...

Retrieve information using PHP with AJAX without revealing it on the screen

Is it feasible to fetch data using Ajax in PHP and store them in a JS variable without displaying it? I require this data for date manipulation but do not want to show it. When I attempted to merely return the data without echoing it, the Ajax data in JS ...

Passport Node: Issue with Password Comparison results in an undefined function error, causing return done(null, user) to fail

I have reviewed all the relevant inquiries and responses but I am still unable to resolve this issue. Please see the code provided below and assist me in understanding why the terminal is displaying 'undefined is not a function'. Here is an overv ...

"The issue with ExpressJS deleteRoute is that it is not properly refreshing user

I have a specific issue with my express controller for deleting user posts. The problem is that while the post is being removed from the page successfully, it is not getting deleted from the User.posts data as expected. function deleteRoute(req, res) { ...

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...

Implementing the expand and collapse functionality to the Discovery sidebar on the DSpace 4.2 xmlui platform

I recently began using DSpace and I am attempting to implement an expand/collapse feature in the Discovery sidebar of DSpace 4.2 xmlui using the Mirage theme. After finding some helpful jquery code, I attempted to add this functionality by placing the js f ...