首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Nuxt动态获取文件夹中的图像路径

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

Stack Overflow用户
提问于 2019-01-01 13:41:31
回答 1查看 5.8K关注 0票数 9

我正在使用nuxt和vuetify。我有一个可以工作的carousel组件.I,它想在静态文件夹中生成.png文件的列表。遵循Dynamically import images from a directory using webpackhttps://webpack.js.org/guides/dependency-management/#context-module-api,我的组件如下所示:

代码语言:javascript
复制
 <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模板中。

我发现,如果我编辑脚本的items数组,使其看起来如下所示,它将工作:

项目:[{ src:'/52iv.png‘},{ src:'/91Iv.png’},....

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

编辑:

我查看了建议的解决方案,但在将其复制到verbatum之后,我得到以下错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-10 09:36:52

以下内容似乎可以正常工作:

代码语言:javascript
复制
<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
      };
    }
  };

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53993252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档