What could be causing my images not to show up when I use string interpolation for src links in Vue.js?

I've encountered an issue while working on Vue.js where I'm struggling to render a couple of images from the local directory. What puzzles me is that this problem arises when using string interpolation, like in the code snippet below:

<img :src="`../../assets/images/${category.imgUrl}.jpeg`" :alt="category.name"> 

...while the following code displays the image as expected:

<img class="app-link app-link--google" src="../../assets/images/googlestore.png" alt="Google play store link">

The resulting src string and relative link appear to be similar in both snippets, so what could I possibly be overlooking?

Here is the complete code for the component under discussion.

<template>
    <div class="explore">
        <h2>Explore by category</h2>
        <div class="categories">
            <div class="category" v-for="category in categories" :key="category.name">
                <router-link :to="`find${category.path}`">
                    <img :src="`../../assets/images/${category.imgUrl}.jpeg`" :alt="category.name">
                    <p>{{category.name}}</p>
                </router-link>
            </div>
        </div>
    </div>
</template>

<script>
    import { categories } from '@/helpers';

    export default {
        name: 'explore',
        data() {
            return {
                categories,
            }
        },  
    }
</script>

<style lang="scss" scoped>
    $body-color: #0f1721;
    $text-color: #ffffff;
    $link-color: #00a2c7;
</style>

Answer №1

If you need to utilize a variable, the require() function must be invoked.

You can either use a static approach:

<img src="../../assets/images/something.jpeg" :alt="category.name"> 

Or, if it's dynamic, use require() like this:

<img :src="require(`../../assets/images/${category.imgUrl}.jpeg`)" :alt="category.name"> 


Why is require() necessary for it to function properly?

The reason will become clearer once you inspect the generated value at src. You'll observe that there isn't a path specified there. Ultimately, it becomes a data:image string.

Since your application uses webpack, it doesn't get deployed as multiple files but rather as one large bundle (file). This means that all components are combined into a single .js file. The images also need to be included in this file. To achieve this, they are "inline" as data:image strings.

When you define the src statically, webpack is aware of the image's path during "compile time" and can immediately inline it.

However, webpack does not recognize :src, so it disregards it. On the other hand, webpack understands what require() does. Essentially, require('somefile') instructs webpack to insert the entire content of somefile at that point. Therefore, using require('someimage.jpeg') results in pasting the contents of that image as a data:image string.

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

I am having difficulty retrieving all the cssRules for certain pages

Attempting to retrieve all CSS rules using JavaScript has yielded varying results. For instance, on StackOverflow, the code used is: console.log( document.styleSheets[1].href,'rules', document.styleSheets[1].cssRules,'Should be css rules, ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

Access the angular controller using the radio button option

I am looking to showcase data in an HTML table retrieved from an Angular controller. I have the controller set up but I am unsure about how to display the data when a radio button is selected. <div class="radio"> <label class="radio-inline" ...

decide whether to use webpack bundling during development or not

Whenever I save a file, it takes around 30 seconds for the changes to reflect. I am currently using gulp watch and webpack for bundling around a hundred files. Is there any way to speed up the build process? ...

With a GroupAvatar, my Avatar named "max" likes to dance to the beat of its own drum rather than following the rules of my

I am currently working on creating an AvatarGroup using MaterialUi. I have successfully applied a style to all my avatars, except for the avatar that is automatically generated by AvatarGroup when the "max" parameter is defined. const styles = makeStyl ...

When using node.js with MySQL, the insert statement with a WHERE clause does not execute properly

Snippet: function setValue(currentVal) { idOutput = currentVal; encodedVal = Base.encode(idOutput); var baseInsert = {ShortUrlCode: encodedVal}; console.log(idOutput); console.log(encodedVal); con.q ...

Guide on sending images as props in a Vue.js component (using Vite instead of require due to compatibility issues)

This is the main component <template> <rooms-card roomImage="../../assets/images/room3.jpg" roomType="Duplex Room" roomDescription="Sami double bed 1 guest room 3 windows" roomPrice="$50/night" /> < ...

.Internet Explorer text update problem

Encountering a problem specifically in IE (like always). I've managed to narrow down the issue I'm facing to a recursive script responsible for updating a tweet's timestamp. The script functions correctly, identifying all the date/time sta ...

Using the `await` command may lead to the variable losing its scope

Utilizing the await keyword to retrieve data from the database has been causing me some trouble. The variable secuity_ok is set to true on one line, but inexplicably changes to false on the following line. What could be causing this issue? It's worth ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Combine PHP, jQuery, and AJAX to retrieve multiple values simultaneously

I have been using jQuery AJAX for my projects. When I make an AJAX call to a PHP page, it normally returns a single value to the success function of AJAX. However, I am now looking to retrieve multiple data individually. How can I achieve this? This is th ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

Error in Node.js: Cannot listen on socket.io object as it does not have a 'listen' method

I am currently developing a Node application using socket.io version 0.9.13 alongside Express 3.0.6. I am encountering an issue where the app fails to run due to an error stating that socket.io does not have a method called listen(). Here is the code snipp ...

What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully ...

Parcel React component library throws an error stating that "require is not defined

Error message: Uncaught ReferenceError: require is not defined at index.js?5WdmUIncGTkIrWhONvlEDQ:1:1 (anonymous) @ index.js?5WdmUIncGTkIrWhONvlEDQ:1 First lines of index.js: require("./index.css"); var $cI6W1$lodash = require("lodash&q ...

Is it allowed to use an ID as a variable identifier?

One method I often use is assigning a variable with the same name as the id of an element, like this: randomDiv = document.getElementById("randomDiv"); randomDiv.onclick = function(){ /* Do something here; */ } randomDiv.property = "value"; This tech ...

The error message "Uncaught TypeError: Cannot read property 'createDocumentFragment' of null" occurs when using Jquery in Django

Struggling to identify the issue with this code that was previously functioning but started malfunctioning after reorganizing the JavaScript at the bottom of the page. It keeps throwing this error: The line triggering the error is: $('.formset_row&ap ...

Every time I try to install create-react-app, I keep encountering a frustrating 'network Socket timeout' error

$ npx create-react-app amazon-clone npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. Creating a new React app in D:\js\faceboom. npm WARN config global `--global`, `--local` are deprecated. ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Interested in learning how to redirect to a different page using vanilla JavaScript after submitting an HTML form with a Django backend?

Recently delving into Django, I encountered a challenge of linking a js file to my HTML form page and saving the form data before moving on to the next screen. My aim was to incorporate a feature where users can click a picture and POST it along with their ...