作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在 Vue 中创建了一个简单的应用程序(使用 Webpack 模板),其中有一个旋转木马。我想做的是遍历 static/images
中的所有图像以创建该轮播。我知道这可能是一个愚蠢的问题,但我该怎么做呢?我是否需要执行 GET
请求?
我问的原因是因为我要把它交给客户托管在他们的服务器上。如果需要,他们希望能够自行将其他图像添加到轮播。
如有任何帮助,我们将不胜感激。
最佳答案
从这里webpack documentation您可以根据正则表达式搜索模式获取目录中的所有文件或特定文件。
你可以这样做:
var cache = {};
function importAll (r) {
r.keys().forEach(key => cache[key] = r(key));
}
importAll(require.context('../components/', true, /\.js$/));
如果您需要来自服务器的图像名称数组,您可以这样做:
<template lang="html">
<div style="height: 100px">
<div :key="key" v-for="(img, key) in images" >
<img :src="imageDir + key.substr(1)" class="" >
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageDir: "/your/path/to/images/", // you know this already just from directory structure
images: {}
}
},
mounted() {
this.importAll(require.context(this.imageDir, true, /\.png$/))
},
methods: {
importAll(r) {
var imgs = {}
r.keys().forEach(key => (imgs[key] = r(key)))
this.images = imgs
}
}
}
</script>
我不完全确定我做的是否正确,但它从目录返回图像并按预期显示它们。
关于webpack - 循环遍历 Vue.js 静态目录中的 Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236354/
我是一名优秀的程序员,十分优秀!