Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the string is not empty, the image fails to load.

In my template:

<img
 :src="article.author_image"
 alt="Author Image"
 @error="setFallbackImageUrl"
>

Within my methods:

methods: {
    setFallbackImageUrl(event) {
        console.log('Image failed to load, setting fallback.')
        event.target.src = '~/assets/icons/avatar.svg'
    }
}

Even though the console log confirms that setFallbackImageUrl is being triggered, the image src remains unchanged. I've verified that the avatar.svg path is correct, as manually setting it works rather than relying on article.author_image.

Do you have any suggestions on what mistake I might be making?

Answer №1

An issue arises when trying to load an image using vue loader and webpack because the file extensions like .png and .svg are not recognized as module requests. For more information on how to handle assets with vue loader, you can refer to this guide.

To resolve this issue, you will need to wrap the image path in a require statement. The example provided by @Toni Michel Caubet works because he uses a link.

This solution worked for me as well.

methods: {
    setFallbackImageUrl(event) {
        console.log('Image failed to load, setting fallback.')
        event.target.src = require(`~/assets/icons/${'avatar' + '.svg'}`)
    }
}

It's worth noting that you don't necessarily have to use "${'avatar' + '.svg'}" in the image path. I simply replaced my dynamic values with "avatar".

Answer №2

If you are encountering difficulties with webpack while working with files from assets/static, be sure to check out the recommended solution provided in this link:

Resolving issues with dynamic img src URL using an "OR" statement in NUXT component

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

Is it possible to utilize JavaScript for transmitting and storing data on a server?

Consider this scenario: When you submit a query on stackoverflow, the data you provide is entered into a text field. This information is then transmitted to the server for storage and eventual display to the user. Is it possible to code the functionality ...

The output of jquery's val() function will not show the actual value

Is it proper to use html() for setting content in non-form elements like divs? This question has come up a few times, which I wasn't aware of. I've been working on setting a value after fetching comments through a $.ajax call. When I check the v ...

In JavaScript, private variables are not included in the JSON.stringify output

Imagine creating a class called Rectangle with private fields like width and height, initializing them in the constructor. However, when calling JSON.stringify on an instance of this class, it returns an empty object without including the private members. ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Clicking on a marker in Google Maps will display the address

I have a map that contains several markers, each designated by their latitude and longitude coordinates. I would like to be able to see the address associated with each marker when I click on it. However, I am currently experiencing an issue where nothing ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

Styling Dropdown Options Based on Conditions in React

In my current project, I am attempting to modify the className of selected items within a mapped array using another array (this.props.notPressAble). The reason for this is because I want certain objects in the array to have a different CSS style. handleOp ...

I'm thinking about transitioning my current React app to Next.js. Do you think it's a good move?

We have recently transitioned our project from react-redux with firebase authentication and solr DB to next.js. Below is the updated folder structure of our app: --src --actions --assets --components --controllers --firebase --redu ...

Can a single button click be shared across multiple forms?

The main concept involves a grid where when a user double-clicks on a row, a modal window (Bootstrap panel) opens with a panel-body section for editing the data and a panel-footer containing a btn-group for actions like "Save", "Cancel", or "Close". This s ...

What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Learn how to generate a table directly from code instead of relying on a .json file

I need help modifying this code snippet that currently reads JSON data from a file. I have generated the JSON data from my database and would like to update the code to read it directly instead of from a file. You can refer to how the JSON is being accesse ...

Managing ajax requests for lazy loading while scrolling through the middle of the window can be a challenging task. Here are some tips on

I have implemented Lazy loading in my Project. I found a reference at which explains how to make an ajax call after scrolling and image upload with slow mode without allowing scrolling until the loader is shown. The code snippet I am using is as follows: ...

Leverage the power of React by utilizing SVGR to easily integrate SVG files

Wondering if there's a way to bring in an SVG file from my public folder and use it as a React component like this: import { ReactComponent as MySvg } from '/assets/svg/mysvg.svg'; const MyComponent = () => { return ( <div> ...

Error encountered: Mongodb db.collection.find() function is not successfully retrieving data, whereas the collection.insert() function

Working with node.js/express and utilizing a Mongodb database to store various data sets. The functionality for adding, editing, and deleting data on a webpage is functioning properly. For instance, the code snippet for adding data is as follows: router. ...

Unraveling strings containing components within a Vue.js template

Can a string with components be parsed into a template in vue.js? For example: "Some text, some <b>bold text</b>, and inserted image from this component <vue-simple-image :src='images/my_image_name.png' />, another text and ht ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

What is the reason for XMLHttpRequest.status being equal to 0 in all browsers except for Internet Explorer?

I am encountering a frustrating issue... After developing a standalone RESTful.NET webservice using C#, I noticed that when I make a XMLHttpRequest to fetch JSON data, all browsers, except for IE, fail to retrieve the data. The problem lies in the status ...

Issue encountered when sending a Laravel route as a prop in VueJS

When trying to implement the blade syntax route() in a vue js component, I attempted the following code: <nav-bar :user="{{ json_encode(Auth::user()) }}" :authPath= "{{ route('auth') }}"> </nav-bar> An error popped up in the cons ...