Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag:

<img 
  :src="require(`@/assets/${project.image || 'day-1.jpg'}`)" 
  alt="project image"
  class="rounded-xl row-span-3 col-span-1"
>

For the initial instance of this component on the website, the {project.image} correctly provides the image file name from the store as: gfs.jpg. However, this particular image does not exist in the file tree.

In this scenario, shouldn't the code above prompt Webpack to render the day-1.jpg image due to using the || operator when the gfs.jpg file is not found?

An error is being thrown by Webpack stating Cannot find module './gfs.jpg' with error code 500

I also attempted to use an @error tag that triggers a handler function within methods: {}, but it does not execute when encountering this particular error.

Answer ā„–1

When using the || operator, exceptions are not caught, this is particularly evident when a required URL does not exist.

To address this issue, one approach is to utilize a method or computed property that manages the error thrown by require, defaulting to day-1.jpg:

<template>
  <img :src="imgUrl">
</template>

<script>
export default {
  props: {
    project: Object
  },
  computed: {
    imgUrl() {
      try {
        return require(`@assets/${this.project?.image}`)
      } catch (e) {
        return require('@/assets/day-1.jpg')
      }
    }
  }
}
</script>

Answer ā„–2

This is how I revised it:

<template>
  <div>
    <img :src="require(`@/assets/${selected}`)" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      project: {
        image: 'forest.jpg', // try testing this with an empty string ''
      }
    }
  },
  computed: {
    selected() {
       // Using optional chaining (?.) would serve as a good fallback for your project
      return this.project?.image || 'morning-1.jpg'
    },
  },
}
</script>

If there are any issues with the images or if your server refreshes too quickly, you might encounter strange errors in the console and the quickest solution would be to restart the server.

For more solutions, refer to: Vue.js dynamic images not working

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

JavaScript forEach functionality is not compatible with Dynamics CRM 2016

I'm currently working on writing some JavaScript code for a ribbon button in Dynamics CRM 2016 that will extract phone numbers from a list of Leads displayed in the Active Leads window. However, I've encountered an error message when attempting ...

The importance of dependencies in functions and testing with Jasmine

In troubleshooting my AngularJS Service and Jasmine test, I encountered an issue. I am using service dependency within another service, and when attempting to perform a Unit Test, an error is thrown: TypeError: undefined is not an object (evaluating sso ...

Activate a button on-the-fly

When the page loads, I have an empty array. Since there are no values stored in this array, I disabled the button using ng-disabled="array1.length==0". Now, on the page that opens up, there are four drop downs present. My goal is to enable the button once ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Is there a way to host a Vue app bundled with webpack in Django without having to recompile for every update?

After setting up my Django project, I decided to develop a Vue frontend to complement it. I initiated the Vue app using vue init webpack myproject-frontend. Working on both projects separately was simple - running python manage.py runserver for Django and ...

tips for retrieving global variables from ajax calls using promises

Currently, I am retrieving data and storing it in global variables in a less than optimal way. Here is the current method: var tranlationJson = $.ajax({ type: "GET", url: "translation.xml", contentType: "text/xml", dataType: "xml", ...

Exploring the Benefits of Using Gatsby with Material-UI: The Importance of Creating a Page

Upon reviewing the gatsby demo showcased on the material-ui project github page, I found myself puzzled by a few lines of code. In the specific file getPageContext.js export default function getPageContext() { // Ensuring each server-side request has i ...

Unable to retrieve options from a particular select box

Utilizing cheerio and nodejs to scrape all the countries listed on a website, I have implemented the following code: const rp = require('request-promise'); const cheerio = require('cheerio'); const options = { uri: 'https://u ...

Error: The current element cannot be clicked. Please try again

I have been attempting to trigger a click event on another button within an onClick event function. An error occurred: Uncaught TypeError: this.clickBack.current.click is not a function The React version being used is 16.8.6 constructor(props) { s ...

Ways to incorporate radio buttons, checkboxes, and select fields into a multi-step form using JavaScript

In the snippet below, I have created a multi-step form where users can provide details. The issue is that currently only text input fields are being accepted. The array of questions specifies the type of input required for each question: Question no.1 req ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...

The value of "asp-route-id" is dynamically determined through the use of

Hey there, Iā€™m looking to dynamically pass a value from "codeDrink" to my controller using "asp-route-id" and Ajax in my ASP.NET MVC project. This is how I am handling it in my view: <p> <a id="deleteLink" asp-action="Delete& ...

Saving the Structure of an XML Document Using JQuery

Xml: <Data> <Cat> <Name>Fluffy</Name> </Cat> <Cat> <Name>Willy</Name> </Cat> </Data> JQuery: // ...Executing ajax requests... $(xml).find('Cat').each(function ...

Different time parameter for setting a timeout in Javascript

I am struggling to create a slideshow with varying time intervals for each image. My knowledge of Javascript is limited, and I have been working on resolving this issue for quite some time. /* function ShowEffect(element){ new Effect.Appear(element, ...

suggestions for organizing data in an AJAX/jQuery page

Welcome to my JavaScript/Ajax webpage that also utilizes jQuery. I am facing a challenge with displaying a nested structure. Once a top level element is displayed, users should be able to click on it and reveal the levels below (which are dynamically gene ...

What is the process of invoking the POST method in express js?

I've been diving into REST API and recently set up a POST method, but I can't seem to get it to work properly. The GET method is running smoothly in Postman, but the POST method is failing. Can someone lend a hand in figuring out where I'm g ...

Challenge with timing in slideUp and slideDown animations (jQuery)

The element with the class "heady" is designed to slide up when the document height percentage is below 25%. If you scroll back up, it should reappear after a delay of 1400ms. The problem arises when this action needs to repeat, as the class does not sli ...

Using PHP functions in an AJAX request

I am currently attempting to execute a php loop upon clicking a radio button. I understand that ajax is necessary for this task, but as a beginner in ajax, I am struggling to achieve the desired result. Presently, I am unable to click the radio button at a ...

Activate the button solely when the text field has been populated without any spaces

Searching for a solution to my query, but all the suggestions I've encountered don't consider spaces as valid input. In the join function I have, the button should be disabled if the user enters only spaces. A requirement is for actual text inpu ...

This is some guidance on toggling the visibility of dynamically created divs in Vuejs when a button is clicked

I am working on a project where I have dynamically created buttons and divs. The goal is to show the corresponding div when a button is clicked, while hiding the rest of the divs. Since the number of buttons and divs is not predetermined as they are gene ...