Navigating the file paths for Vue.js assets while utilizing the v-for directive

Recently, I started working with Vue.js and found it simple enough to access the assets folder for static images like my logo:

<img src="../assets/logo.png">

However, when using v-for to populate a list with sample data, the image paths seem to be causing trouble. Here is my template:

<ul>
    <li v-for="item in items" :key="item.id">
       <img v-bind:src="item.img" v-bind:alt="item.title">
       <h2 class="md-title">{{item.title}}</h2>
    </li>
</ul>

Here is the sample data declared within the same .vue file:

export default {
  name: 'front',
  data () {
    return {
      items: [
        {title: 'Google Pixel', img: '../assets/pixel.png', id: 1},
        {title: 'Samsung Galaxy S8', img: '../assets/s8.png', id: 2},
        {title: 'iPhone 7', img: '../assets/iphone.png', id: 3}
      ]
    }
  }
}

All the image URLs are resulting in a 404 error, despite working fine for static images. Using an absolute path like this one works:

https://media.carphonewarehouse.com/is/image/cpw2/pixelBLACK?$xl-standard$

I checked the documentation and came across this reference

Though I tried all the suggested methods for resolving assets, none of them seemed to work:

Asset Resolving Rules

  • Relative URLs, e.g. ./assets/logo.png will be interpreted as a module dependency. They will be replaced with an auto-generated URL based on your Webpack output configuration.

  • Non-prefixed URLs, e.g. assets/logo.png will be treated the same as the relative URLs and translated into ./assets/logo.png.

  • URLs prefixed with ~ are treated as a module request, similar to require('some-module/image.png'). You need to use this prefix if you want to leverage Webpack's module resolving configurations. For example if you have a resolve alias for assets, you need to use to ensure that alias is respected.

  • Root-relative URLs, e.g. /assets/logo.png are not processed at all.

Could this be an issue related to webpack rather than Vue? It seems odd that such a user-friendly library would make dealing with filepaths complex.

Answer №1

I reached out to the Vue.js forum for help and was fortunate enough to receive a response from Linus Borg:

Linus explained that when it comes to asset paths used in HTML or CSS, webpack-loaders can handle them. However, if the paths are within Javascript code, webpack cannot automatically interpret them as paths. This means we need to explicitly specify these strings as paths to dependencies using require().

export default {
  name: 'front',
  data () {
    return {
      items: [
        {title: 'Google Pixel', img: require('../assets/pixel.png'), id: 1},
        {title: 'Samsung Galaxy S8', img: require('../assets/s8.png'), id: 2},
        {title: 'iPhone 7', img: require('../assets/iphone.png'), id: 3}
      ]
    }
  }
}

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 AngularJS promise/defer feature alongside the Quickblox framework, learn how to efficiently upload images and subsequently upload public URLs to a custom

I am currently developing an application that requires users to upload 5 images of themselves. Using a backend-as-a-service platform like Quickblox, I have to create and upload blob files individually. Once each image is uploaded, I receive a success call ...

Validator alert for AMP scripts

I have implemented the amp version for my content management system. Since each article has a different body, some include amp-instagram while others include amp-facebook, and so on. In order to cover all bases, I have added both amp-facebook and amp-inst ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...

The program failed to run properly because it couldn't find the reference to Chart

I added chart.js to my project using npm with the command: npm install chart.js --save-dev. In the file "resources/assets/js/bootstrap.js", I included it by using: require('chart.js');. After running npm run dev in the console, it compiled succe ...

The jquery fancybox ajax modal popup fails to display in Internet Explorer 7

Recently, I utilized JQuery fancy box for the first time to display a menu list. When clicking on a specific item, the page is rendered properly in an iframe. However, if there is already an AJAX model popup present on the rendered page, it doesn't di ...

What is the best way to determine whether a YouTube video permits embedded playback?

When working with user-generated content, it's important to note that YouTube channels may restrict their videos from being played in an embedded player. In order to provide a better user experience, I need to detect the specific reason why a video ca ...

The proper way to define an event delegator's syntax

Typically, when you want to handle a button click event, you would do so like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); However, in the scenario of an event delegator, you may need to respon ...

What is the proper method for terminating an Express app.all?

Here's a snippet of my code where I utilize the app.all method. In this scenario, I am invoking the fetchBuildings function based on the building ID or hash provided in the URL. Subsequently, I am assigning values to the title, description, and image ...

Emphasize the designated drop zone in Dragula

Incorporating the Dragula package into my Angular 2 project has greatly enhanced the drag-and-drop functionality. Bundling this feature has been a seamless experience. Visit the ng2-dragula GitHub page for more information. Although the drag-and-drop fun ...

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

The ajaxStart() and ajaxStop() methods are not being triggered

I'm currently working on a Q/A platform where users can click on specific questions to be redirected to a page dedicated for answers. However, when a user tries to answer a question by clicking the "Answer" link, certain background processes such as ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Ways to combine duplicate entries within a column using Ruby on Rails?

I need some help with a filtering issue related to sign names. I am trying to merge the content together if there is more than one name of the sign. You can refer to the image attached for better clarity, where I have two server names but I only want to di ...

Completion of the form within the Bootstrap popover

I have a feature where dynamically created rows contain an "add" button. When the user clicks on the add button, a form is loaded into a Bootstrap popover. See FIDDLE DEMO My issue is: Why isn't this code being triggered? I am trying to validate ...

Distorted element being dragged in vue.draggable

I am currently working on rearranging the colors in a palette using drag and drop functionality. You can find the pen I am using here: - https://codepen.io/neon22/project/editor/XbqvYe <script type="text/x-template" id="cpalette"> <div> ...

What are the steps to customize the format of Vue3 Datepicker extensions?

Is there anyone who can lend a hand? I am currently using the Vue3 Datepicker and I have received a value that looks like this Thu Jun 23 2022 17:14:00 GMT+0700 (Western Indonesia Time) Does anyone know how to transform it into the following format? Thu, ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

Display a div element using AngularJS

Looking for a way to display a div using AngularJS, I came across some solutions on StackOverflow. However, implementing them did not work in my case. Here is my HTML code: <div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" clas ...

Executing a C# function from an HTML hyperlink

I am in the process of developing a website using ASP.NET C#. The site will feature a GridView with data that can be exported, such as to Excel or other formats. To handle the export functionality, I plan to utilize code from this resource. When a user c ...

Performance problem with 'Point-along-path' d3 visualization

I recently explored a d3 visualization where a point moves along a path, following the code example provided at https://bl.ocks.org/mbostock/1705868. During this movement, I observed that the CPU usage ranges from 7 to 11%. In my current project, there ar ...