如何使用 vue.js/nuxt.js 获取目录中的所有图像文件

Sye*_*yed 9 javascript vue.js vuejs2 nuxt.js

我正在处理一个 nuxt.js 项目并出现错误:

在浏览器中,我看到此错误:

__webpack_require__(...).context is not a function
Run Code Online (Sandbox Code Playgroud)

而且,在终端中,我收到此错误:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted 
Run Code Online (Sandbox Code Playgroud)

这是我的代码

<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>
Run Code Online (Sandbox Code Playgroud)

我从HERE使用了上面的脚本。

请帮忙,谢谢。


编辑:按照@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>
Run Code Online (Sandbox Code Playgroud)

Max*_*nev 13

来自 webpack 文档:

传递给的参数require.context必须是文字!

所以我认为在你的情况下解析require.context失败。

尝试传递文字而不是imageDir变量

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

这是必要的,因为 webpack 在捆绑期间无法解析您的运行时变量值。


Jan*_*cha 7

vue 3 与 vite 的解决方案:

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

了解更多: https: //github.com/vitejs/vite/issues/77