如何使用 vue.js / nuxt.js 获取目录中的所有图像文件
How to get all the image files in a directory using vue.js / 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>
来自 webpack 文档:
The arguments passed to require.context
must be literals!
所以我认为在你的情况下 require.context
的解析失败了。
尝试传递文字而不是 imageDir
变量
mounted() {
this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
},
这是必要的,因为 webpack 无法在打包期间解析您的运行时变量值。
我正在处理一个 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>
来自 webpack 文档:
The arguments passed to
require.context
must be literals!
所以我认为在你的情况下 require.context
的解析失败了。
尝试传递文字而不是 imageDir
变量
mounted() {
this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
},
这是必要的,因为 webpack 无法在打包期间解析您的运行时变量值。