Tips for saving an image link when displaying an image in VueJS using the 'require' method

I am currently working on a project that involves displaying Pizza items with their respective images. Each Pizza object is stored in the database along with an imgUrl field. Strangely, the images are not showing up on the page, although I can see the alt text that I provided. When I check the console, the image link appears to be correct.

Currently, the data in the imgUrl field of the database looks something like ../assets/images/pizza.jpg. Would it make more sense to save

require(../assets/images/pizza.jpg)
instead? It seems odd to me. Below is the code snippet, particularly focusing on the mounted method.

<template>
  <div>
    <div class="class">
      <span><h1>All you can eat Menu.</h1></span>
      <div class="container">
        <div class="box" v-for="item in pizzaList" :key="item.id">
          <div>
            <img :src="item.imgUrl" alt="Image"/>
              <div>
                <a class="btn" @mouseenter="$event.currentTarget.style.background = '#EF6B7F'"
                @mouseleave="$event.currentTarget.style.background = '#e31837' ">Buy Now</a>
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data () {
    return {
      pizzaList: []
    }
  },
  mounted: function () {
    axios.get('http://localhost:8081/api/pizza/all')
    .then(response => {
      this.pizzaList = response.data;
    })
    .catch(e => {
      console.log(e);
    })
  }
}
</script>

I have already referred to some articles on Stack Overflow regarding similar issues:

  • Vue and API: Displaying Image
  • Image path in Vue JS
  • How to reference static assets within vue javascript

Although these resources provide guidance on encapsulating hardcoded URLs with require, they do not address the scenario where the URL is fetched from the database. How should we incorporate require in the HTML tag in such cases? Your insights would be greatly appreciated. Thank you.

Answer №1

The issue with the code not functioning properly was due to

Webpack's require() requiring a static portion of the file path, with only partial dynamic parts allowed

Basically, you can't store the complete image path in the database and then pass it to require in the UI for it to work as expected

To fix this, I made the following change:

<img :src="require(`${item.imgUrl}`)" alt="Image"/>

with item.imgUrl being '

../assets/entities/pizza/pizza_1.jpg
' (the full relative path to the component)

was replaced by

<img :src="require(`../assets${item.imgUrl}`)" alt="Image"/>

where item.imgUrl is '/entities/pizza/pizza_1.jpg'

For a more detailed explanation, refer to the insights shared by Michal Levy in the comments section at

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

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

The topic at hand pertains to a specific exercise featured in the well-known book Eloquent JavaScript

In this exercise, the final step is to create a recursive function that takes a joined list and an index as parameters. The function's purpose is to find the value in the object within the list at the specified index. The code I have written seems to ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

When my webpage is opened in Firefox, I notice that it automatically scrolls down upon loading

I recently embarked on the task of building a website from scratch but ran into an unusual bug in Firefox. The issue causes the page to scroll down to the first div, completely bypassing its margin. I want to clarify that I am not seeking a solution spe ...

Encountered an issue with launching Chrome in Puppeteer for Node.js

My code was uploaded to EC2 AWS, but unfortunately it is not working properly after the upload. Interestingly, it runs correctly on localhost. Despite trying various solutions, I am still facing this issue. Any suggestions on the correct approach to resolv ...

Leverage JSON data and implement it in JavaScript

In my PHP page, I have a JavaScript function that includes a JSON method for retrieving data from the database. The code snippet looks like this: $this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class ...

Is there a way to update the background dynamically?

I'm currently developing a weather application and I want the background to change dynamically based on the data retrieved from an API. Initially, I set up a variable and utilized an if statement for this purpose. However, I encountered difficulty in ...

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

Incorporating functions from another JavaScript file within an AJAX request

There's a function called _HideErrorBox() in the file 1.js that I want to use in the file 2.js within an AJAX call. I'm loading both 1.js and 2.js in a specific order. Here's the content of 1.js: var Calculations = function() { var _H ...

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

Having trouble accessing cookies in JavaScript on Internet Explorer 11?

I am facing an issue with my Angular application where cookies are not being read properly in Internet Explorer 11. The JavaScript code works fine on Chrome, but IE seems to be having trouble accessing the cookie data even though it is visible in the devel ...

A step-by-step guide on recursively removing all empty array children [] from a nested JSON structure

When I receive a JSON response, I utilize nested JSON data from my GeoRegionCountries APIController and a custom class TreeView to structure the data for a plugin. The specific plugin I am using is a combo multi-select Treeview, accessible through this lin ...

Position an HTML canvas at the very top of the webpage

Can someone help me figure out how to align a canvas element to the very top (0, 0) of a webpage? I attempted using margin: 0; padding: 0px;, but it didn't work. There always seems to be some white space at the top that I can't eliminate. ...

Expanding an array in JavaScript

I need assistance with... let a = ['a', 2, 3]; a += function(){return 'abc'}; console.log(a[3]); Therefore, I am looking for a shorthand method to push() in array with the above content. Does anyone know of an operator that can help ...

Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues. I have set the root font-size as 23px The current font-size is 16px The expected result should be 16 / 23 => 0.695rem Question: I am looking for ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

Exploring SVG Morphing Reversal Techniques in Anime.js

I have been trying to implement direction: 'reverse' and timeline.reverse(), but so far it hasn't been successful. Interestingly, when I set loop: true, the reverse animation can be seen within the loop. However, my goal is to trigger this a ...

I am struggling to decide which attribute to use for implementing image swap on mouseover() and mouseout()

I have a problem using jQuery to switch between images when hovering on and off. Here's the code snippet I'm working with: HTML <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt=""> jQuery $(" ...

Javascript syntax error: Unexpected ending of data while trying to parse JSON data at line 1, column 1

I operate a CS:GO betting platform, and I encountered an issue when attempting to access the page for withdrawing skins. After completing the reCAPTCHA verification process to confirm that I am not a robot, I received the following error: Javascript err ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...