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

Leveraging the power of React in conjunction with an HTML template

After purchasing an HTML template from theme forest, I am now looking to incorporate React into it. While I find implementing Angular easy, I would like to expand my skills and learn how to use React with this template. Can anyone provide guidance on how ...

multiple urls causing duplication of states in angular ui routes

Currently, I am faced with an issue while using angularjs in combination with angular ui routes. The problem arises when dealing with multiple URLs for a single route. I have a state named "bookDetails" which corresponds to a book that has a unique id an ...

By default, the text area element in Vue or Nuxt will send a message to the console

Every time I include a textarea html element in my Vue/cli or Nuxt projects, this message appears in the console. Is there a way to prevent this message from showing up in the console? <textarea rows="5" cols="33"> This is a textarea. < ...

Learning how to allocate a key index within an array using Vue.js

Hey there! I've got a form set up like this: <tr v-for="(post, index) in posts" v-bind:index="index"> <td>{{ post.rut }}</td> <td>{{ post.names }} {{ post.father_lastname }} {{ post.mother_lastname }}& ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

cracking reCAPTCHA without needing to click a button or submit a form (utilizing callback functions)

Currently, I am facing a challenge with solving a reCaptcha on a specific website that I am trying to extract data from. Typically, the process involves locating the captcha inside a form, sending the captcha data to a captcha-solving API (I'm using ...

Specify the CSS bundle during the compilation of a Vue application

I am faced with the challenge of using a single code-base for my Vue application, but needing to compile it with different styles depending on the end user. Each end user (which in this case refers to a group or organization) has their own specific CSS fil ...

The HTML Canvas arc function fails to properly align curves

UPDATE Upon further investigation, I've discovered that this problem only occurs in Chrome. Could it be a browser issue rather than a coding problem? I'm working on creating a circle with clickable sections using HTML5 Canvas. The circle itself ...

Firebase (web) deploy encounters an issue due to stripe integration

I recently integrated Stripe into my Firebase function index.js: const stripe = require('stripe')('key'); and created a function for checkout sessions: exports.createCheckoutSession = functions.https.onCall(async(data, context) =&g ...

The Vuetify asynchronous search feature is only able to send single characters at a time, and it doesn't concatenate the characters

In my Vue component, I have the following code: <template> <v-form ref="form" @submit.prevent="search"> <v-row class="pa-0"> <v-col cols="12" md="2" class="d-flex"> <v-autocomplete ...

Save the test outcomes in HTML format using cypress

Can Cypress test results be exported to an HTML or another format, similar to cucumber-report.html? ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...

display object issue with object display

I'm encountering a strange issue with my constructor objects in JS - when I try to view them, all I see is [object Object]. Can anyone help me figure out why this is happening? Check out the code snippet on MyCodeFiddle. ...

Understanding Java and JavaScript variables within a JSP webpage

I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables ...

What is the process of comparing one regular expression against another in JavaScript?

I'm looking to check for matches between two regular expressions. To achieve this, I use the .test method on each one. If either of them returns true, I consider them a match. const regexify = (str) => new RegExp( '^' + str ...

Encountering a display:flex problem with postcss in Vue CLI 3

Issue with Vue CLI 3 Configuration In my current setup, utilizing vue cli 3 with all default configurations including autoprefixer and postcss, I have encountered a challenge. The problem arises when using Samsung internet version greater than 7, as the ...

Refresh required to showcase newly created items

Currently, I am developing a straightforward tool that allows users to assign budgets to teams. This tool operates in a manner similar to a standard to-do list. The delete function functions smoothly without requiring a reload. However, the create functio ...

The functionality of fetching website titles using Ajax/jQuery is experiencing some limitations

Below is a code snippet for a simple website title getter: $( document ).ready(function() { $("#title").click(function() { var SubURL = $("#input").val(); $.ajax({ url: "http://textance.herokuapp.com/title/"+SubURL+"/", complete: function(da ...

Tips for extracting innerHTML or sub-string from all elements that have a specific class name using JavaScript

When it comes to shortening the innerHTML of an element by its Id, I have found success using either slice or substring. While I'm not entirely clear on the differences between the two methods, both accomplish what I need them to do. The code snippet ...

A guide on deploying a Next.js application using Passenger

I'm completely new to development and I'm attempting to deploy my very first application (let's call it testing). I am looking to deploy my Next.js React app using Passenger (which is included and required by Dreamhost, so I have not insta ...