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

时间:2019-01-08 15:46:10

标签: javascript vue.js vuejs2 nuxt.js

我正在研究nuxt.js项目并收到错误消息:

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

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

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

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

这是我的代码

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

我使用了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>

1 个答案:

答案 0 :(得分:2)

从webpack文档中:

  

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

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

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

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

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