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

Issue with Electron application encountered during relocation of build directory

Currently, I am developing an Electron-App using NPM that functions as an installer by unzipping a file to a specified directory. While everything works smoothly when I build the application and run it from the win-unpacked folder, moving the folder to a d ...

Experiencing issues with autoungrabify or autolock in cytoscape.js?

I have been working on a web application using Cytoscape.js, and I recently integrated the Edgehandles extension to allow users to add edges. The two types of edges that can be added are undirected and directed. Adding directed edges is functioning as expe ...

No charts are displaying in Vue with Apex Charts, despite following the tutorial closely

Currently, I am a newcomer to Vue development, and my goal is to display a page containing 4 charts. I envision them being shown in a 2x2 format, with 2 charts side by side and the other 2 stacked below each other. To kick things off, I decided to work on ...

Unexpected TypeError occurred when trying to Fetch data from an Express Server hosted on Window object

Error Message : Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name Feeling stuck as I looked around, unsure of what's causing this issue. My goal is to develop a website that can eventually make a ...

A guide on breaking down the ID passed from the backend into three segments using React JS

I pulled the data from the backend in this manner. https://i.stack.imgur.com/vMzRL.png However, I now require splitting this ID into three separate parts as shown here. https://i.stack.imgur.com/iy7ED.png Is there a way to achieve this using react? Bel ...

Gather every hyperlink and input fields without utilizing jQuery

Is there a way to target all a and form elements without relying on jQuery? My end goal is to achieve the following functionality: document.querySelectorAll('a').forEach(element => { element.addEventListener('click', () => { ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

Managing HTML5 Video in a slider

I've designed a unique video slider that cycles through 4 videos. Each video has a custom play button and additional overlay content. Once the video starts playing, the overlay content and play button fade out to reveal the default video controls. The ...

`Set-cookie` isn't effective in dist compilation produced by the `npm run build` command

Currently, my vue frontend server utilizes cookies to manage the login state in conjunction with a basic backend server. The issue arises when set-cookie functions properly in production mode while running npm run serve. However, upon bundling the project ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...

Ways to resolve the angular error "Encountering an unhandled exception: Unable to locate module 'typescript' "?

I'm encountering errors when running ng serve. I've attempted the following code as well, but I'm still facing the same error: npm install -g typescript Error displayed in text format D:\xampp\htdocs\angular\axen>ng ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Using an object method within a different object in JavaScript

I am attempting to create two objects, one from each of my classes - a Person object and a Drink object. I then want to invoke the drinking method by passing in a Drink object. However, I am struggling with how to do this. Here is my code, and I can't ...

Which API is utilized by duojs for its JavaScript modules?

I am currently utilizing duojs, a front-end web development tool similar to browserify or component. With duojs, you can directly import css and js from the file itself without any external package manifests. While I'm trying to figure out how to wri ...

Leveraging the power of Google Closure Templates alongside the versatility of

We are embarking on developing an application using JavaScript and HTML5 that will utilize a rest API to access server resources, leveraging the power and convenience of jQuery which our development team is already proficient in. Our goal is to make this a ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...