简体   繁体   English

如何使用vue.js/nuxt.js获取一个目录下的所有图片文件

[英]How to get all the image files in a directory using vue.js / nuxt.js

I am working on a nuxt.js project and getting error:我正在开发一个 nuxt.js 项目并遇到错误:

In browser I am seeing this error:在浏览器中我看到这个错误:

__webpack_require__(...).context is not a function

And, in terminal I am getting this error:而且,在终端我收到这个错误:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted 

Here is my code这是我的代码

<script>
export default {
  name: 'SectionOurClients',
  data() {
    return {
      imageDir: '../assets/images/clients/',
      images: {},
    };
  },

  mounted() {
    this.importAll(require.context(this.imageDir, true, /\.png$/));
  },

  methods: {
    importAll(r) {
      console.log(r)
    },
  },
};
</script>

I have used the above script from HERE .我从HERE使用了上面的脚本。

Please help, thanks.请帮忙,谢谢。


EDIT : After following @MaxSinev's answer, here is how my working code looks:编辑:遵循@MaxSinev 的回答后,我的工作代码如下所示:

<template lang="pug">
  .row
    .col(v-for="client in images")
      img(:src="client.pathLong")
</template>

<script>
export default {
  name: 'SectionOurClients',
  data() {
    return {
      images: [],
    };
  },

  mounted() {
    this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
  },

  methods: {
    importAll(r) {
      r.keys().forEach(key => (this.images.push({ pathLong: r(key), pathShort: key })));
    },
  },
};
</script>

From the webpack docs:来自 webpack 文档:

The arguments passed to require.context must be literals!传递给require.context的参数必须是文字!

So I think in your case parsing of require.context failed.所以我认为在你的情况下解析require.context失败。

Try to pass literal instead of imageDir variable尝试传递文字而不是imageDir变量

mounted() {
    this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
},

It is necessary because webpack can not resolve your runtime variable value during bundling.这是必要的,因为 webpack 在捆绑期间无法解析您的运行时变量值。

Solution for vue 3 with vite: vue 3 与 vite 的解决方案:

<script setup lang="ts">
const fonts = import.meta.glob('@/assets/fonts/*.otf')
console.log(fonts)
</script>

Read more: https://github.com/vitejs/vite/issues/77阅读更多: https ://github.com/vitejs/vite/issues/77

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM