Having trouble with V-For image paths not locating the image files? Need help on adding the right file path while using v-for?

I am currently using Vue/Nuxt and facing an issue with populating an image carousel. The images I want to insert into the carousel are stored in a folder named "AreaPictures" within my assets directory.

This is how my v-for loop is structured:

<div class="area__slider">
  <div v-swiper="swiperOption">
    <div class="swiper-wrapper">
      <div v-for="image in images" :key="image" class="swiper-slide">
        <img :src="`../assets/AreaPictures${image.imageURL}`" alt="" />
      </div>
    </div>
  </div>
</div>

Below is my script section for reference:

<script>
    export default {
      name: 'Area',
      data: function () {
        return {
          videoLanguage: 'English',
          englishSrc: 'https://www.youtube.com/embed/lRKmJqDbVsY',
          spanishSrc: 'https://www.youtube.com/embed/q0WkEkIMmQo',
          currentSrc: 'https://www.youtube.com/embed/lRKmJqDbVsY',
          swiperOption: {
            grabCursor: true,
            loop: true,
            autoplay: {
              delay: 5000,
              disableOnInteraction: false,
            },
            pagination: {
              el: '.swiper-pagination',
            },
          },
          //----- ARRAY TO STORE THE IMAGE PATHS
          images: [],
        }
      },


      //-----IMPORT THE IMAGES ON MOUNT
      mounted() {
        this.importImages(require.context('~/assets/AreaPictures/', true))
      },
      methods: {
        changeSrc() {
          if (this.videoLanguage === 'English') {
            this.currentSrc = this.englishSrc
          } else {
            this.currentSrc = this.spanishSrc
          }
        },


        //-----THIS IS WHERE I IMPORT THE IMAGES
        importImages(r) {
          r.keys().forEach((key) => {
            var path = key.substring(1) //-----THE PATH FOR SOME REASON CONTAINS A . SO I REMOVE IT
            this.images.push({ 
              imageURL: path, //----- CREATE A NEW OBJECT AND ADD IT TO IMAGES
            })
          })
        },
      },
    }
    </script>

The console error message states:

vue.runtime.esm.js?2b0e:6785 GET http://localhost:3000/assets/AreaPictures/area1.jpg 404 (Not Found)

It seems that I am getting the correct file names but encountering issues with the file path. I have also attempted using @/assets/AreaPictures/area1.jpg, but it failed as well.

If anyone can provide insight on how to dynamically reference file paths in this scenario, your help would be greatly appreciated!

Answer №1

Solving the issue of dynamic images not working in Vue.js I had a similar problem, but I found a solution that worked for me. Make sure to include require() around your image sources to ensure proper loading with Webpack.

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

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Ways to cycle through information within a table using a multi-dimensional array

I am currently facing a challenge with iterating data into a table from a multidimensional array. Here is the specific string I am working with. str = 'stack%splitoverflow,php%splitcodeigniter' My approach involves first splitting the string b ...

Customize Nivo LightBox to apply to only one video separately on the page

I've recently implemented the Nivo LightBox script on my website for a video popup effect. However, as a newcomer to jQuery, I'm struggling to customize the lightbox to only trigger when clicking a specific link for my video, rather than every li ...

Guide to updating HTML table data using php and Javascript

Currently, my webpage fetches data from a MySQL database and displays it in an HTML table as soon as the page loads. Now I want to provide users with more advanced filtering options, such as filtering by name, age, etc. When a user submits their filterin ...

Experimenting with sails.socket using npm for testing purposes

Currently, I am utilizing sails.js v0.11.0 and delving into unit testing. While I have a good grasp on testing normal controllers through http requests, I am at a loss on how to approach testing the same calls via socket requests. Any recommendations for ...

Leveraging Javascript/jquery to retrieve image data for a specific frame within a video

Query My aim is to optimize the code for image manipulation on a web browser using JavaScript. One possible solution I am considering is utilizing a video file to reduce HTTP requests. Is there a way to extract a single frame from a video in png, jpg, or ...

Ensure that the "Write after end" error is avoided by not calling response.end() prematurely when setting up

Hello, I am new to the world of coding and recently started exploring StackOverflow. My current focus is on learning Node.js and experimenting with its inbuilt methods like createServer and response.end(). In my quest to apply what I have learned so far, I ...

Manage Blob data using Ajax request in spring MVC

My current project involves working with Blob data in spring MVC using jquery Ajax calls. Specifically, I am developing a banking application where I need to send an ajax request to retrieve all client details. However, the issue lies in dealing with the ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

Issue with accessing local server using NuxtJS 3 $fetch function

As someone who is new to Nuxt3, I recently attempted to establish a connection between my Nuxt3 frontend application and my backend site built with Laravel. The frontend URL is set at http://localhost:3000 while the backend can be found at http://localhost ...

ASP/VB.NET Client-Side Script Generation/Registration

I am currently updating outdated "Web 1.0" code to align with modern standards. Is there a more efficient way to create and add a client-side script without having to concatenate numerous lines into a StringBuilder and then registering it to the page usin ...

javascript get the current date and year

Examining the javascript code below: <script type="text/javascript"> $(function () { var currentDateTime = new Date(); var oneYear = new Date(); oneYear.setYear(oneYear.getYear() + 1); alert(currentDateTime + "_" ...

What is the best way to utilize a single Google Map component instance across multiple children?

Seeking a method to maintain the same Google Map instance throughout my entire app, as each map load incurs charges... Currently utilizing google-map-react. An instance of a new Map is created in ComponentDidMount, suggesting that it's important to k ...

The React-native-vision-camera is unable to connect to the rear-facing camera

Currently, I am facing a challenge using the 'normal' camera on my iPhone 11 Pro. I have implemented react-native-vision-camera in my project. When executing the following code: const devices = useCameraDevices(); const deviceBack = devices.back; ...

Is there a way to merge these arrays into a single array?

With the current code I am obtaining numerous JSON objects within separate arrays: Here is the code snippet: for (let i=1; i<=150;i++){ fetch(`A valid URL ${i}`) .then(result => result.json()) .then(result => console.log(result.data.results)) ...

A beginner's guide to importing modules in Node.js

Whenever I attempt to import into my nodejs file, I consistently encounter the error message stating "cannot import outside a module." I have experimented with various solutions found on StackOverFlow, such as including "type":"module" ...

Having issues with AngularJs functionality in a basic project

After creating a simple helloworld with angular, I am unable to see the result. The angular.min.js file is included in the html and loads correctly in the browser. Here is my code: <!DOCTYPE html> <html> <head lang="en"> <met ...

The functionality of res.status().send() appears to be malfunctioning when used within a Promise

I am currently working on a code that involves checking authorization from two different API calls within a promise.all method. If any of the authorizations fail, I want to throw the respective res.send method as an error. However, I keep encountering an " ...

Issue encountered while attempting to load external JSON file from server in AngularJS

Currently, I am attempting to load a JSON file from the server. Below is my services.js file: angular.module('starter.services', []) /** * A simple example service that returns some data. */ .factory('Friends', function($http) { ...

Trigger the function of a Jquery plugin once AngularJS has finished rendering

Upon receiving an object collection via Ajax, I store it in a variable: // Variable available for the template this.list = []; // Function to refresh the list var self = this; this.refreshList = function () { ChannelService.get({}, function (result) { ...