Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly.

<template>
    <div id="index">

        <img :src="image.src" v-for="image in images">

    </div>
</template>

<script>
export default {

    name: 'Inicio',

    data() {
        return {
            images: [
                {src: '@/assets/xxx.png'},
                {src: '@/assets/xxxx.png'},
                {src: '@/assets/xxx.png'}
            ]
        }
    }
}
</script>

When I use the path specified in the src attribute such as '@/assets/xxx.png', it doesn't load the image properly.

However, if I manually type the src directly like this

<img src="@/assets/xxx.png">
, the image loads correctly.

Answer №1

When using v-for, it's essential to keep in mind that static assets cannot be referenced directly. This is because webpack needs to rewrite static paths before runtime. The values of image.src will only be processed and included in the template during runtime, meaning webpack does not compile relative paths into real paths in the bundle.

To address this issue, one effective solution is to utilize require():

<template>
    <div id="index">

        <img :src="image.src" v-for="image in images">

    </div>
</template>

<script>
export default {

    name: 'Inicio',

    data() {
        return {
            images: [
                {src: require('@/assets/xxx.png') },
                {src: require('@/assets/xxxx.png') },
                {src: require('@/assets/xxx.png') }
            ]
        }
    }
}
</script>

Check out the demo sandbox here: https://codesandbox.io/s/811px8kn88

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

Ways to determine if an element has exceeded its container's boundaries

After creating the codesandbox, I have developed a webapp that heavily relies on user input. To keep it simple for demonstration purposes, I am displaying various authors on an A4 formatted page using `page` and `font-size` with the `vw` unit for responsiv ...

"Comparison: Java Installation vs. Enabling Java in Your Web Browser

Is there a method to determine if Java is currently running on your system or if it has been disabled in your browser? Our application relies on Java applets, and we typically use "deployJava.js" to load the applet. However, even when Java is disabled in t ...

VueJS: Toggling button visibility in a table

I am facing an issue with my code where clicking on button A should hide it and display button B, but nothing happens when I click on A. Here is the code snippet: <template> <table> <thead> <tr> <th> ...

Having trouble connecting Agora.io with nuxt.js? A common issue may arise in the `created` hook with the error message "ReferenceError: AgoraRTC is not

I am currently working on integrating Agora Web SDK with nuxt.js. After including all the necessary methods, my page now consists of various methods and lifecycle hooks: methods: { // Stream initialization function streamInit(uid, attendee ...

Editing an XML file on the browser and saving it in its original location on the local file system

Seeking assistance with editing an XML file directly from the browser on a local file system and saving it back to its original location. I have conducted extensive research using Google, but have not been able to find a suitable solution. Any help or gu ...

The Vue.js route is not aligning with its defined path, causing a mismatch

Attempting to develop a Vue SPA app, but encountering an issue with the routes not matching what was defined in the router. Despite all configurations seemingly correct, there is confusion as to why this discrepancy exists. What element might be overlooked ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Tips for utilizing mock service worker to test Vue Apollo?

While setting up a mock service worker to test my composition functions, I encountered an error stating: Apollo client with id default not found. Use provideApolloClient() if you are outside of a component setup.. I believe using provideApolloClient shoul ...

The AJAX call was successful with a return code of 200, however an error

HTML code snippet: <a href="javascript:void(0)" onclick="$.join_group(<?=$USER_ID?>, <?=$groups[$i]["id"]?>)"><?=$language["join"]?></a> JavaScript function: $.join_group = function(user_id, group_id) { var input = "u ...

Enable a button or class to dynamically alter its color

Hi there! I'm new to coding and just started learning HTML and CSS. My question is: How can I change the color of buttons once they are clicked? <div class="icon-bar"> <a href="#"><i class="fa fa-search" ...

I encountered no response when attempting to trigger an alert using jQuery within the CodeIgniter framework

Jquery/Javascript seem to be causing issues in codeigniter. Here is what I have done so far: In my config.php file, I made the following additions: $config['javascript_location'] = 'libraries/javascript/jquery.js'; $config['javas ...

Showing the selected item and navigating to the items before and after in an array using Vue

I have a pair of elements arranged in two rows side by side: https://i.stack.imgur.com/ymhv3.jpg Both elements have been added to an array of objects and passed through props to be displayed on the left side. My goal now is to set it up so that when a c ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

RTK Query may sometimes encounter undefined values when fetching data

I am new to using Redux and facing an issue while trying to display data in a Material UI Select. When I try to show the user's name, it works perfectly, but when I do the same for the partner's data, they appear as undefined. In my server index ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...

conceal the .card-body element if the children have the CSS property "display:none"

My challenge involves managing two collapsible cards on a webpage. I am looking for a solution where the .card-body will have its display set to none when there are no inner divs to show in the card upon clicking a letter in the pagination. Otherwise, the ...

Changing webpage content without using asynchronous methods once authentication has been completed using Google Firebase

My goal is to create a website where users can sign in with Google by clicking a button, and then be redirected to a new HTML page. However, I am facing an issue where the Google sign-in window pops up briefly and closes immediately, causing the HTML page ...

Encountering a 401 error when submitting a form in Laravel Vue using Axios

Whenever I try to submit user data in my modal, I encounter a 401 error. Here is the code snippet that's causing the issue: sendUserData(){ axios.post('/api/saveUser', { headers: { ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

Working on asynchronous processing of Highland stream fragments

My current setup involves utilizing highland.js to process a file using a stream and extract content between specific delimiters. Additionally, I am incorporating async.js to perform a sequence of http requests. I am seeking a way to pass the output x fro ...