Obtain image file paths dynamically in a folder using Nuxt

https://i.sstatic.net/3FKZH.png

Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing images from a directory using webpack and exploring the Webpack context module API guide, my current component setup appears as follows:

 <template>
  <v-carousel>
    <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
  </v-carousel>
</template>


<script>

  var cache = {};
  function importAll(r) {
    r.keys().forEach(key => cache[key] = r(key));
  }
  var getImagePaths = importAll(require.context('../static/', false, /\.png$/));
  // At build-time cache will be populated with all required modules. 
  export default {
    data: function() {
      return {
        items: getImagePaths
      };
    }
  };
</script>

The objective here is to navigate through the static folder, extract image paths, store them in an array, and then output them to the HTML template.

Upon modifying the script's items array as demonstrated below, the solution proved effective:

items: [ { src: '/52iv.png' }, { src: '/91Iv.png' }, ....

To achieve the desired outcome, how can I tailor my code accordingly?

EDIT:

After considering the suggested solution and replicating it word for word, I encountered the following error.

https://i.sstatic.net/ThiTL.png

Answer №1

Here is a solution that seems to be functioning properly:

<template>
  <v-carousel>
    <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
  </v-carousel>
</template>


<script>
  var cache = {};
  const images = require.context('../static/', false, /\.png$/);
  var imagesArray = Array.from(images.keys());
  var constructed = [];
  
  function constructItems(fileNames, constructed) {
    fileNames.forEach(fileName => {
      constructed.push({
        'src': fileName.substr(1)
      })
    });
    return constructed;
  }
  
  var res = constructItems(imagesArray, constructed);
  console.log(res);

  export default {
    data: function() {
      return {
        items: res
      };
    }
  };

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

Adding numbers to a textbox using a JavaScript algorithm

There are two textboxes in this scenario. The first box should always contain 4 digits when you leave it, while the second box should always contain 10 digits. A javascript function needs to be implemented so that when a user leaves one of the textboxes, ...

Leverage JavaScript variables within JSON objects

I have a JavaScript variable that I want to use in a JSON format. var add = mixItems[i][0] + "," + mixItems[i][1]; jQuery.getJSON("wp-content/plugins/proteinmixer/php/addtocart.php" , function(data){ }); Here is the PHP code: require_once('../../.. ...

Looping through a series of URLs in AngularJS and performing an $

Currently, I am facing an issue while using angular.js with a C# web service. My requirement is to increment ng-repeat item by item in order to display updated data to the user. To achieve this, I attempted to utilize $http.get within a loop to refresh t ...

Is it permissible to assign the same element as a child to multiple parent elements in jQuery?

Imagine you have the following HTML structure: <div id="first"></div> <div id="second"></div> Now, if you use JavaScript and JQuery to perform the following actions: var $child = $("<span id='child'>Hello</span ...

What is the best way to switch between List and Grid view while automatically updating the image displayed?

**#Unique Component Implementation** import React from 'react'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import { makeStyles } from &apo ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

Initiate a CSS animation only when a different animation has completed

I am trying to create a sequence of animations using 2 squares. I want the animation for the red square to start only after the blue square's animation is complete. How can I achieve this cycle of animations? .box { width: 100px; height: 1 ...

Bringing TypeScript modules from a local module into a React application

As I work on organizing my projects and keeping logic separate in components that will eventually be published, I have a specific structure set up for now: I have a library of Typescript scripts within a project named project-a A separate React app create ...

Issues with integrating VUE frontend with PHP backend and API

Apologies for any language mistakes as English is not my native tongue. I hope my message is clear enough. We are in the process of developing a user system where users, upon logging in, can perform various actions such as joining events, updating their p ...

The issue with property unicode malfunctioning in bootstrap was encountered

I have tried to find an answer for this question and looked into this source but unfortunately, when I copy the code into my project, it doesn't display Unicode characters. section { padding: 60px 0; } section .section-title { color: #0d2d3e ...

How can I trigger an API call 30 seconds after my React Native app switches to the background?

Seeking assistance with my React Native app: I am trying to make an API call 30 seconds after the app goes into the background. I am using AppState from react-native to detect when the app goes into the background, but I'm not receiving any callback a ...

Locate every item that has a value that is not defined

My data is stored in indexeddb, with an index on a text property of the objects. I am trying to retrieve all objects where this property's value is undefined. I have been experimenting with IDBKeyRange.only(key), but when I use null, undefined, or an ...

Troubleshooting: Vue JS failing to recognize new objects and properties in HTML

Within my Vue instance, I have a method named `loadPlannedAlerts` that performs an AJAX call to retrieve JSON data. This method is called during the `mounted` lifecycle hook of my Vue JS instance. The retrieved JSON object consists of key-value pairs struc ...

Tips for invoking a particular function when a row in a Kendo grid is clicked

I have a Kendo grid named "mysubmissionsGrid" and I want to execute a function when each row is clicked with a single or double click. How can I accomplish this? <div class="col-xs-12 col-nopadding-left col-nopadding-right" style="padding ...

Interactive Vue tree view featuring draggable nodes

I am currently working on creating a tree component in Vue.js, and I am facing challenges with implementing drag and drop functionality in the Tree component. I am unsure where to begin, as I have looked through similar code on GitHub but I am struggling t ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

Implement a basic JavaScript prompt feature within a Node.js application that can be integrated into

My Angular App is wrapped by electron and utilizes node.js to fetch MySQL data for AngularJs via electron. However, since there is no fixed database in my project, I have to dynamically change the database credentials from the client side, making sure it p ...

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

javascript trigger not functioning

Currently, I am working with ASP development and incorporating jQuery into my projects. One challenge I've encountered is not being able to utilize the trigger function upon page load. Interestingly, my change function seems to work smoothly, except ...

What is the best way to insert an anchor tag into text using React?

I am working with a variable const linkElement = `Hey this is a link ${<a href="www.google.com">Click me!</a>} that can be clicked}` Currently, it displays as Hey this is a link [Object object] that can be clicked. Is there a way to ...