使用 Nuxt 动态获取文件夹中的图像路径

Dynamically get image paths in folder with Nuxt

我正在使用带有 vuetify 的 nuxt。我有一个工作轮播组件。我想在静态文件夹中生成一个 .png 文件列表。在 and Following https://webpack.js.org/guides/dependency-management/#context-module-api 之后,我的组件如下所示:

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

我想搜索静态文件夹并获取图像的路径,将它们放入数组中并将它们导出到 html 模板。

我发现,如果我编辑脚本的项目数组以查看以下内容,它将起作用:

项目:[ { 来源:'/52iv.png' }, { 来源:'/91Iv.png' }, ....

如何调整我的代码以获得我需要的结果?

编辑:

我查看了建议的解决方案,但在逐字复制后出现以下错误。

以下似乎有效:

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