Utilizing VueJs @error handler for managing broken image links

I am encountering a strange issue with the VueJS @error handler. My goal is to hide images with broken links and display a placeholder instead. However, when I have two images with broken links, only the first image displays the placeholder while the other one shows the browser's default broken image logo.

Below is the test code I used. I understand that this may not be the best way to write Vue code, but it served its testing purpose.

<div id="app">
    <img width="25%" id="img" src="https://upload.wikimedia.org/wikipedia/commons/5/54/Wallpaper-img_0254.jpg" @error="handle()">
    <img width="25%" id="img" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" @error="handle()">
    <img v-show="ifImageBroken" src="https://via.placeholder.com/300">
    <p>{{brokenText}}</p>
    <HelloWorld/>
</div>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
    name: "App",
    data() {
        return {
            ifImageBroken: false,
            brokenText: ''
        }
    },
    components: {
        HelloWorld
    },
    methods: {
        handle: function() {
            document.getElementById('img').style.display = 'none';
            this.ifImageBroken = true;
            this.brokenText = 'unable to load image';
        }
    }
};
</script>

I'm curious to know if the @error directive can handle multiple instances of broken images.

Answer №1

I encountered a similar issue and found a solution using the object element. The @error attribute only detects broken links, not broken images within links. So, I devised a method to toggle between them.

<object data="https://here the right image if not found will display the image inside img tag.jpg" type="image/png">
    <img src="https://via.placeholder.com/300" alt="Not found image">
</object>

In this setup, it first checks if the :data in the object element is present. If not, it switches to the <img> tag where you can place your placeholder image.

Update 2: I have implemented your code and made some enhancements. I hope it functions as expected.

  <div id="app">
    <img width="25%" id="img" src="https://upload.wikimedia.org/wikipedia/commons/5/54/Wallpaper-img_0254.jpg" @error="imgPlaceholder">

    <img width="25%" id="img" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" @error="imgPlaceholder">
    <p>{{brokenText}}</p>
    <HelloWorld/>
  </div>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  data () {
    return {
      ifImageBroken: false,
      brokenText: ''
    }
  },
  components: {
    HelloWorld
  },
  methods: {
    imgPlaceholder(e) {
        e.target.src = "https://via.placeholder.com/300"
    }
  }
};
</script>

Here, I introduced a new method that intercepts an event and replaces the current broken URL image with another one.

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

"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page. My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and v ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

Displaying the servlet response within an iframe

This is the content of Content.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> &l ...

How to avoid the need to wrap all setState calls with #act in React 18?

One issue I encountered was when upgrading from React 17 to 18, ReactDom render became asynchronous. To handle this, I needed to use #act to wrap the ReactDom render. However, React also required that all setState calls be wrapped with #act. If not done, ...

Sorting a VueJS table excluding certain rows is a breeze

Here is a sample code snippet for a v-table with sortable implementation: <script> export default { data() { return { sortBy: 'age', sortDesc: false, fields: [ { key: 'last_name', sort ...

Execute HTML and JS files through Eclipse PDT to view in a web browser

Is it possible to open HTML and JS files in a web browser within Eclipse PDT? Right now, only PHP files seem to launch successfully, otherwise an "Unable to Launch" dialog pops up. Any advice is appreciated! ...

There seems to be an issue with the HighCharts chart export feature as it is not showing the Navigator graph

We are currently using HighCharts version 4.2.2 http://api.highcharts.com/highcharts/exporting While going through their exporting documentation, I made a decision to not utilize their default menu dropdown. Instead, I only needed access to the .exportCh ...

Is it possible to call a JavaScript file located inside a Maven dependency's jar?

In the process of developing a Spring MVC web application using Apache Tiles, I have incorporated JavaScript libraries such as JQuery by including them in the pom.xml file as dependencies. My query pertains to whether I can access these scripts from within ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Issue with Angular routing not functioning properly post form submission

Recently, I created a contact form using Angular for the frontend and NodeJs with Nodemailer for the backend. However, I encountered an issue where after submitting the form, instead of redirecting to the default page set in the app, the page remains on th ...

What could be causing this error to occur when running my React app and clicking the submit button on the form?

CodeBlock.js import React from "react"; import { useState } from "react"; import axios from 'axios' const CodeBlock=()=>{ const [formData, setFormData]=useState({name:'', password:''}); const hand ...

In JavaScript, the gallery feature with Lightbox effect creates a unique touch as only half of the screen fades to black in

Hello everyone, I'm a complete beginner when it comes to programming so please be gentle with me on my first question :) I'm trying to put together a simple website with a lightbox gallery, and you can check out what I have so far here. The prob ...

How can we effectively implement alert notifications for validating image sizes and formats prior to uploading?

code playground : https://codesandbox.io/s/quizzical-lamport-ql5ep I'm encountering an issue with the code provided in the CodeSandbox link. https://i.sstatic.net/xg3aK.png I've attempted to resolve this issue using various methods, but unfortu ...

Errors occur when attempting to install plugins from npm

I am currently coding in Visual Studio 2017 using Ionic v2 to develop an app for beacon scanning. However, every time I try to install a plugin, I encounter errors from npm about the versions of node and npm being incompatible. Here are my current versions ...

concealed highcharts data labels

I attempted to create a bar chart using Highcharts, and initially it worked fine. However, I encountered an issue when displaying multiple indicators - the datalabels for certain data points are hidden. For example, the datalabel for "provinsi aceh" is not ...

What is the reason behind the execution of componentDidMount occurring after componentWillUnmount?

I have been exploring the differences between componentDidMount and componentWillUnmout by experimenting with the following code: class App extends React.Component { constructor(props) { super(props); this.state = { name: "", ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Utilizing jQuery ajax to dynamically update map markers on Google Maps at intervals

I am currently working on a project that involves updating a Google map with a marker at regular intervals. I have an Ajax request that retrieves a single latitude and longitude coordinate, but I'm struggling to display it on the map. One option coul ...

npm unable to retrieve Meteor package

When I attempted to install meteorite using nodejs v0.10.22 and npm v1.3.14, the installation failed with the following error: $ npm install meteorite npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm ...