Switch out the image for a placeholder whenever the src is updated

I need to update an image with a dynamic src value

<img :src="image.url">

Currently, when the image.url changes, the old image remains in place until the new one loads. This delay can create a strange effect as the text details change before the image updates.

Is there a way to substitute the image with a loading indicator whenever the src property changes using vue.js?

I know I could manually manipulate the DOM with the code that triggers the change, but I'd prefer to handle it the correct way using vue bindings.

Answer №1

To steer you in the right direction, consider the following:

  1. Include an attribute called imageLoading in your data() function.
  2. Define your :src as shown here:
    <img :src="imageLoading ? ./myPlaceholder.png : image.url" />
  3. Use $watch to monitor changes in image.url and update the loading image when necessary:
watch: {
  'image.url': function() {
    this.imageLoading = true;
  }
  1. Implement an @load handler on your img tag to set imageLoading to false once the image is loaded:
    <img :src="imageLoading ? ./myPlaceholder.png : image.url" @load="imageLoading = false" />

A side note on the @load handler - credit goes to this question, which provides a helpful example.

Answer №2

This component serves as a simple placeholder for images, utilizing slots to showcase any placeholder content

<template>
  <div class="image">
    <img :src="src" @load="ready = true" v-show="ready">
    <slot v-if="!ready" />
  </div>
</template>

<script>
export default {
  props: ['src'],
  data: () => ({
    ready: false
  }),
  watch: {
    src () { this.ready = false }
  }
}
</script>

Instructions on how to use it:

<image-placeholder src="IMAGE_URL">
  <b>INSERT PLACEHOLDER CONTENT HERE</b>
  <p>Can be anything</p>
  <img src="ANOTHER_IMAGE_URL" />
</image-placeholder>

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

Instructions for showcasing a 404 error page in the event that a back-end GET request to an API fails due to the absence of a user. This guide will detail the process of separating the

I am currently working on an application that combines JavaScript with Vue.js on the front-end and PHP with Laravel on the back-end. When a GET request is made from the front-end to the back-end at URL /getSummoner/{summonerName}, another GET request is t ...

Hidden content from Vue router view

My goal is to have the navigation pane overlaying the content of the page, but instead, it is being appended to the bottom where the end of the navigation drawer would be. I've experimented with different variations to display data using navigation dr ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...

How can I assign a distinct identifier to individual instances of Vue.js components?

I am looking to build a Vue.js component that includes a label and an input. Here is an example of the structure I have in mind: <label for="inputId">Label text</label> <input id="inputId" type="text" /> Is ...

Vue.js: Select a different div within the Vue object instead of the one that is bound

I am currently utilizing Vue and Leaflet to showcase polygons (zones) on a map and exhibit relevant information (messages) upon clicking on specific polygons. The div responsible for rendering these messages has the unique id "#messagearea" and is connec ...

A Guide to Organizing Vue Js: Dividing 'methods', 'data', 'computed', and More into Separate JavaScript Files

Is it feasible to separate methods, data, computed properties, etc. into individual .js files and then import them into a component.vue file? I prefer not to include all JavaScript logic in a single .vue component. My ideal code organization for each com ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

Utilizing Vue 3, Quasar 2.2.2, and Firebase for accessing GlobalProperties via the router

Hello there! I am currently working on implementing Firebase for the first time in my Quasar App (powered by Vue 3). I have set up the firebase.js boot file with the following content: import { boot } from 'quasar/wrappers' import { initializeApp ...

Utilizing Laravel to Retrieve Information from an API

I am currently working with a database table that requires continuous updating. game_id | end_time My challenge now is figuring out how to create a job that will run based on the end_time. This job will need to retrieve data from a third-party API, and i ...

What are some creative ways to customize v-slot:cell templates?

Currently, I have the following code snippet within a table: <template v-slot:cell(checkbox)="row" style="border-left='5px dotted blue'"> <input type="checkbox" v-model="row.rowSelected" @input="toggleS ...

Encountering the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" while using Django and Vue on my website

While working on my project that combines Vue and Django, I encountered a persistent error message when running the code: "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yel ...

After refreshing the page, vuex is encountering null values when using firebase.auth().onAuthStateChanged

Encountering an issue with Vuex and Firebase Authentication integration. When reloading the page, there is a delay in response from firebase.auth().onAuthStateChanged. I require an immediate response upon page reload without using router guards as seen in ...

Utilizing Axios to send multiple concurrent requests in Vue.js

What is the best way to simultaneously send multiple requests using axios and vue? ...

Encountering an error while running Laravel Mix's npm development script

When attempting to run npm run development, I encountered the following error: let mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |------------------------- ...

[VUE Alert]: Rendering Error - "Sorry, there is a type error: object is currently undefined."

<script> const app = new Vue({ el: '#app', data:{ results:{} }, mounted() { axios.get('{{ route('request.data') }}').th ...

I am interested in incorporating `connect-history-api-fallback` into my project in Vue.js, but I am unsure about the implementation

After refreshing the page in Vue.js, I encounter an Nginx error. I am currently using 'connect-history-api-fallback', but I'm uncertain about how to implement it in Vue.js. I noticed its usage in app.js with middleware server; how can we use ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

What does the `Class<Component>` represent in JavaScript?

Apologies for the lackluster title (I struggled to think of a better one). I'm currently analyzing some Vue code, and I stumbled upon this: export function initMixin (Vue: Class<Component>) { // ... } What exactly does Class<Component> ...

accessing elements in a loop in vuejs

I am trying to create a rating system using Vue.js and the v-for directive. Here is the code I have: <div class="rating-container"> <input type="radio" name="star" value="5" id="star-5"> <label class="star-radio" for="star-5">5&l ...