Tips for implementing a fallback image in v-img using Vuetify

Within my Vuetify application, I am utilizing a v-img component and I am looking to implement a fallback image in case the primary one fails to load.

<v-img :src="cPicture" contain v-on:error="onImgError"></v-img>


cPicture : function() {
            return this.failed_image ? "https://assets.dryicons.com/uploads/icon/svg/9872/ab3c0a16-6f14-4817-a30b-443273de911d.svg" : "http://myimg.jpg/";
        },


onImgError : function(event) {
            alert(1);
            this.failed_image = true;
            //this.$forceUpdate();
        },

The alert message appears as expected. However, an error is also thrown by Vuetify in the console, and the fallback image is not displayed.

How can I resolve this issue?

Note that the main image link intentionally leads to a non-existent location, but if a valid link is provided, it will be successfully rendered.

Answer №1

Consider utilizing cPicture as a computed property and onImgError as a method :

new Vue({
  el: '#app',
  data() {
    return {
      failed_image: false
    }
  },
  computed: {
    cPicture: function() {
      return this.failed_image ? "https://picsum.photos/500/300?image=4" : "https://pisum.photos/500/300?image=5";
    },



  },
  methods: {
    onImgError: function(event) {

      this.failed_image = true;

    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8a899988959a85bccdd2cfd2cb">[email protected]</a>/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-layout>
      <v-flex xs12 sm6 offset-sm3>
        <v-card>
          <v-container grid-list-sm fluid>
            <v-img :src="cPicture" contain v-on:error="onImgError"></v-img>
          </v-container>
        </v-card>
      </v-flex>
    </v-layout>
  </v-app>
</div>

Take a look at this pen

UPDATE

I mistakenly provided an invalid image link for the desired image, which will result in an exception shown in console :

"[Vuetify] Image load failed

In such cases, we will load another image with a valid link.

Answer №2

My approach is similar, but I achieve it with a more concise code.

<v-img tile :src="logo.url" v-on:error="logo.url='/logo.svg'" />

Answer №3

This question was recently raised on the Vuetify GitHub page and it's something that should definitely be included in the upcoming Vuetify 3 release.

I came up with my own solution to tackle this issue in the meantime.

First, I initialize two pieces of data:

data(): {
 avatarLoadingFailed: false,
 fallbackAvatar: fallbackAvatar,
}

The fallbackAvatar variable references the image file that will be displayed if the loading fails.

Next, I create a computed property to determine which avatar to display:

computed: {
  avatar() {
    return this.avatarLoadingFailed
      ? this.fallbackAvatar
      : this.getUserAvatar;
  },
}

Finally, within my template tag, I have implemented the following code:

// @error="avatarLoadingFailed = true" works fine as well
<v-img :src="avatar" v-on:error="avatarLoadingFailed = true"/>

I have thoroughly tested this solution in VueJS, both with and without TypeScript integrated.

Answer №4

I really admire the solution provided by @maurilio-atila. In a similar situation where the image was sourced from a different server, I found a workaround that worked for me:

 <v-img :src="`${item.image ?`https://some/endpoint/${item.image}` : '/fallback.png'}`"/>

Although it doesn't cater to v-on:error, it effectively prevents any error from occurring.

Answer №5

A new feature has been introduced in Vuetify 3 that allows users to utilize the v-img error slot. In the example below, if there are any errors with the first source image, the second source within the error slot will be displayed instead.

<v-img src="https://pisum.phots/500/300?imige=4">
  <template v-slot:error>
    <v-img src="https://picsum.photos/500/300?image=5"></v-img>
  </template>
</v-img>

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

Unable to establish connection with server through Ajax request on HTML page

I set up a NodeJs server using the Express module. However, I am facing issues with implementing an AJAX request from an HTML page using $.ajax when clicking a button. I want to retrieve data from the server in either JSON or text format but for some reaso ...

Sending users to a new destination following an interaction

I'm working on implementing a redirect after a user successfully logs in. I tried calling this.$router.push('/profile') with a callback function post login, but encountered an error message that says Error Cannot read properties of undefined ...

ViewCheck and every

Can IsInView be set to wait for all elements with the same class, instead of calling them individually? For instance, if there are three sections, can they be called like this: $(".section").on('inview', function(event, isInView) { i ...

Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab. Here's the code snippet I have written: <template> <nav class="horizontal top-border block-section"> <div class= ...

Encounter Issue: "Describe" function not recognized. This error occurred during the activation of Mocha Test

https://i.sstatic.net/WBSm6.png Upon my installation of mocha, I encountered an issue while running a test using a command, resulting in the error message "describe is not a function." ...

Retain selected choices even after refreshing the page using PHP

Working on a smaller project using PHP, I encountered a problem that has left me feeling lost. Let me break it down into two parts. Part 1: In my project, I have an index.php file and a getitem.php file. The index file contains a form with multiple select ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

Guide to creating a Chrome extension that can detect updates in MongoDB documents

I have developed a chrome extension for syncing links, which stores the data in a MongoDB database using a custom REST API. While I am successfully able to push changes to the database and listen to them using a change stream in the REST API, I am facing d ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

The selected plugin appears to be incompatible with mobile browsers

My project involves implementing the Chosen plugin for a select field, allowing users to type-search through lengthy lists. It functions perfectly on desktop but is disabled on both Apple and Android phones, reverting to the default user interface for sele ...

When incorporating sequelize's belongsTo and hasOne methods, you may encounter an issue where the call stack size surpass

Within my Discussion entity, I have: Discussion.hasOne(sequelize.import('./sound'), { relations: false }) While in the Sound entity, the relationship is defined as: Sound.belongsTo(sequelize.import('./discussion')) To load t ...

Adjust camera to align with the loaded object in Three.js

I've been struggling to center the camera around the model loaded through the stl loader. I've tried adjusting variables and setting different positions for the mesh and camera, but the camera still isn't centered on the design! Here's ...

Managing numerous JavaScript objects within a plugin

I have developed a straightforward javascript plugin that enables me to gather data from specific html elements. A page can contain x number of elements (usually up to 20), each with its own settings. However, the issue I am facing is that the returned obj ...

What exactly does Container-Based Authorization entail?

Did you know that the "XMLHttpRequest" object includes a method called "open," which has the option to supply a username and password? These parameters can be used for requests that require container-based authentication. Here is the method signature: op ...

Managing PHP multiple follow-up options in HTML select fields

My goal is to design a form that includes multiple follow-up select fields. These fields will be populated from an array with 3 elements: ID, Name, and followingID. The followingID corresponds to an ID in the array, helping us determine the hierarchical la ...

Codeigniter code to retrieve dynamic data in a select box

I am trying to implement a functionality where selecting an option from one dropdown will dynamically populate the options in another dropdown based on the selection. I believe I need to use an onchange function, but I'm unsure how to retrieve data fr ...

What are the essential files needed in Kendo UI Core for a mobile app?

Several months ago, I created a trial Kendo mobile app but now I want to verify it using the most recent version of Kendo UI Core. In my previous project, I referenced the following files: <link href="../styles/kendo.common.min.css" rel="stylesheet" / ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received. Currently, when I press the button, both wait and scroll actions happen immediately without waiting for ...

What is the best way to save JSON data within HTML elements?

I want to enhance my FAQ by making it easily editable. Currently, the content can only be edited in the HTML file. I am looking to load all the information from a JSON file so that any changes or additions to questions and answers can be made directly in t ...