Dynamically get image paths in folder with Nuxt

半世苍凉 提交于 2019-11-30 03:51:29

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/53993252/dynamically-get-image-paths-in-folder-with-nuxt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!