Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get image paths in folder with Nuxt

enter image description here

I'm using nuxt with vuetify. I have a working carousel component .I want to generate a list of The .png files in the static folder. Following Dynamically import images from a directory using webpack and Following https://webpack.js.org/guides/dependency-management/#context-module-api my component looks like:

 <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
      };
    }
  };
  //     export default {
  //       data() {
  //         return {
  //           items: [{
  //               src: "/52lv.PNG"
  //             },
  //             {
  //               src: "https://cdn.vuetifyjs.com/images/carousel/sky.jpg"
  //             },
  //             {
  //               src: "https://cdn.vuetifyjs.com/images/carousel/bird.jpg"
  //             },
  //             {
  //               src: "https://cdn.vuetifyjs.com/images/carousel/planet.jpg"
  //             }
  //           ]
  //         };
  //       }
  //     };
  //
</script>

I want to search through the static folder and grab the paths to the images , put them in an array and export them to the html template.

I've found that if I edit the script's items array to look the following it will work:

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

How can I adjust my code to get the result I need?

EDIT:

I looked at the proposed solution , but after copying it verbatum I got the following error.

enter image description here

like image 269
user1592380 Avatar asked Jan 01 '19 05:01

user1592380


1 Answers

The following appears to work:

<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
      };
    }
  };

like image 184
user1592380 Avatar answered Nov 05 '22 12:11

user1592380