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

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...

Challenges encountered while creating a Number Tables Program (such as displaying 12 x 1 = 12) using Javascript

Currently, I am working on developing a program that can generate mathematical tables for any given number. For example: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 To achieve this, the user should provide the following inputs: (1) The number they want ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

Unable to activate click function in Jquery

Here is a basic HTML page snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script> <script> $(document).ready(function () { $('#test').click(); }); < ...

Angular service providing a subset of resource data

I am currently working with an Angular factory called DogePrice: .factory('DogePrice', ['$resource', function ($resource) { return $resource("https://chain.so/api/v2/get_info/DOGE"); }]) Usually, the API response looks like this: ...

Encountering the error message: "TypeError [ERR_INVALID_ARG_TYPE]: The initial parameter should either be a string, Buffer instance, or Uint8Array."

Having trouble with the payment gateway API and subscription creation. Encountering an error that I can't seem to resolve even after debugging. Despite my best efforts, the error persists. The form and everything else seem to be in order, but the err ...

How to manually add the $store parameter to a dynamically created Vue component that is missing it during creation

I'm a newcomer to the world of Vue/Nuxt and I've encountered an issue while attempting to dynamically generate a Vue component on button click using the following code: async addComponent(componentsItem) { var ComponentClass = Vue.component(&a ...

Setting the opacity of an image will also make the absolute div transparent

I currently have an image gallery set up with the following structure : <div class="gallery"> <div class="message"> Welcome to the gallery </div> <img src="http://placehold.it/300x300" /> </div> Here ...

Instructions for capturing multi-dimensional arrays using forms in Vue

I have a snippet of code that looks like this: <div class="form-item"> <label for="list-0"><?php _e('List 0', 'test'); ?></label> <input name="list[0]" type="text" id="list-0" value=""> </div> &l ...

Activate jQuery function upon clicking a bootstrap tab

When I click on a Bootstrap tab, I want to trigger an AJAX function. Here is the HTML code: <li><a href="#upotrebljeni" data-toggle="tab">Upotrebljeni resursi</a></li> The jQuery AJAX function looks like this: $('a #upotreb ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Sort ng-repeat based on the initial character

Working in AngularJS, I am handling an array of objects and aiming to display filtered data based on the first letter. My initial method used was as follows. HTML: <p ng-repeat="film in filmList | startsWith:'C':'title'">{{film. ...

How can I trigger a CSS animation to replay each time a button is clicked, without relying on a timeout function?

I am having trouble getting a button to trigger an animation. Currently, the animation only plays once when the page is refreshed and doesn't repeat on subsequent clicks of the button. function initiateAnimation(el){ document.getElementById("anima ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Pressing the "Enter" key in a .Net WinForm Browser Control

How can I simulate the Enter key press event on a web page using the GeckoFX Web Control? I am unable to use SendKeys.Send({ENTER}) Is there a method to trigger the Enter key using JavaScript within a webpage? ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

Is there a solution to prevent the "NavigationDuplicated" error in Vue.js when adding query parameters to the URL without changing the path?

Presently, the URL shows /search The new URL should display /search?foo=bar I am looking to modify my query parameters on the current route after applying some filters on the page. This is my code: this.$router.push({query: params}) Although I can h ...

Making multiple Node.js requests using the request module: A comprehensive guide

Purpose: My goal is to extract data from approximately 10,000 web pages using Node.js. Issue: The scraping process speeds through the first 500~1000 pages but then significantly slows down beyond that point, sometimes halting completely. To initiate the ...

Differences in file loading in Node.js: comparing the use of .load versus command-line

Currently, I am in the process of developing a basic server using vanilla JavaScript and Node.js. For this purpose, I have created a file named database.js, which includes abstractions for database interactions (specifically with redis). One of my objecti ...