Determine the validity of an image URL using Vue.js

Is there a way to check if an image URL is valid or broken in Vue.js, similar to the process outlined in Angular 2 - Check if image url is valid or broken?

Answer №1

Vue.js provides a convenient @error event that you can utilize. This information is sourced from an article on vuejs issue#3261. Here's an example of how you can use it:

<template>
   <img :src="avatarUrl" @error="imageLoadError" />
</template>

<script>
export default {
  methods: {
    imageLoadError () {
      console.log('Image failed to load');
    }
  }
};
</script>

Note: It has come to my attention that this also applies to <audio> tags (and potentially other elements with a src attribute and asset loading)!

Update: Upon further investigation, I've realized that this event serves as a way to attach a listener to the native onerror event emitted by many HTML elements, akin to using

<input @blur="someHandler">
, etc.

Answer №2

It appears that the @error function is functioning correctly. I have personally utilized a technique involving an event to designate an alternative image.

<img :src="imageUrl" @error="imageUrlAlt">

The approach:

imageUrlAlt(event) {
    event.target.src = "alt-image.jpg"
}

Referenced from Vue.js issue#5404.

Most effective resolution:

<img :src="imageUrl" @error="imageUrl='alt-image.jpg'">

I appreciate all the valuable feedback from everyone.

Answer №3

In my approach, I implement a computed property to generate a string containing the placeholder URL instead of using an @error handler. By doing this, the placeholder will be displayed in case the source is null or undefined.

<img :src="source || computedPropertyString" />

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

Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness. document.addEventListener( 'mousewheel', onDocumentMouseWheel, fal ...

What is the best way to initiate a dialogue (updating component state) using Vue Router?

I am looking to enhance page state management using vue router. For instance: / should navigate to the home page. /login will keep the user on the home page while triggering a dialog with the login form. /register will also trigger the dialog, but this t ...

What could be causing the response data from an AJAX request to be in error instead of success?

My JSON data is securely stored on , and I can access it through a unique URL. Here is the specific URL: The JSON data found at the above URL is: { "glossary": { "title": "Suyog", "GlossDiv": { ...

Encountering a compilation error when attempting to import a shader from a file in a project using THREE.js, Vue.js

I've encountered an error and spent hours searching for a solution, but unfortunately found nothing. The correct way to import shader code from a file is: import {ColourShader} from '../shaders/ColourShader.js' Here is the content of my &a ...

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...

Tips for swapping hosts in Postman and JavaScript

Is there a simple way to allow the front-end and testing teams to easily override the host header to match {tenant}.mydomain.com while working locally? I'm looking for a solution that doesn't involve constant changes. Any ideas on how I can achie ...

Styled-components causing issues with conditional rendering

Within my React component, I have multiple properties and I want styles to only apply if a property has a value. I attempted the following code: export const Text = ({text, color, size, fontFamily}) => { const StyledParagraph = styled.p` m ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Manipulating data in node.js as it arrives in separate chunks

Hey there, I am trying to make some changes to the data received from the server. All incoming data via the POST method is processed in chunks. <button id='helloButton'>Send hello!</button> <button id='whatsUpButton'>S ...

Error message: React Native encountered a prop type failure when an invalid prop of type array was passed to the Overlay component

I am brand new to React Native and encountering an error message when opening a specific component. Although it doesn't hinder navigation, I would like to resolve this issue. I suspect it could be related to a syntax or typo error, but pinpointing the ...

How can I verify if a date is after the current date using Node.js?

I am struggling to set up date validation that ensures the date is after the current date. This is what I have attempted so far: Router.post('/home', [ check('due_date') .isDate() .isAfter(new Date.now()) .wi ...

Choosing dynamically created components:Making a choice among elements that are generated

Currently, I am working on a task that involves moving list items between two separate lists and then returning them back upon a click event trigger. Below is a snippet of the basic HTML structure: Unchosen: <br> <ul id="unchosen"></ul> ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

retrieve data from the API response using a node request

I initiated an API request using the request method. Everything seems to be functioning properly, but I am encountering difficulty extracting the results from the response. The snippet of my code in question is as follows: app.get('/events/:query&a ...

Save the JSON response from JavaScript to a different file extension in a visually appealing layout

I've created a script to generate both the CSR and private key. The response displayed in the <textarea> is well-formatted with newline characters (assuming familiarity with the correct CSR/Private key format). However, I'm encountering a ...

Issue with Sheetjs: Date format is not recognized when adding JSON data to a

I am struggling to export JSON data to Excel while maintaining the correct date format of 2020-07-30 07:31:45. Despite trying suggestions from a helpful post on sheetjs, I still couldn't get it right. Here is an example of the JSON data: { "so ...

Material selection through span in three.js is not functional

Initially, the span element was functioning properly for me. However, after setting up materialsLib and initMaterialSelectionMenus based on the documentation and examples, the span stopped working and now the model is not visible. Any assistance would be g ...

Issue: Unable to access 'filter' property of null object

I've been working on a small react dropdown task and it's running smoothly in Google Chrome. However, I encountered an error when testing it on MS Explorer. Even after deploying it on a live server, the issue persisted. The specific error message ...