循环遍历 Vue.js 静态目录中的资产 [英] Looping through assets in Vue.js static directory
问题描述
我在 Vue 中创建了一个简单的应用程序(使用 Webpack 模板),其中有一个轮播.我想做的是遍历 static/images
中的所有图像以创建该轮播.我知道这可能是一个愚蠢的问题,但我该怎么做呢?我需要执行 GET
请求吗?
我之所以这么问是因为我要把它交给一个客户端来托管在他们的服务器上.如果需要,他们希望能够自己向轮播添加其他图像.
任何帮助将不胜感激.
从此 webpack 文档 您可以根据正则表达式搜索模式获取目录中的所有文件或特定文件.
你可以这样做:
var cache = {};函数 importAll (r) {r.keys().forEach(key => cache[key] = r(key));}importAll(require.context('../components/', true,/.js$/));
如果您需要来自服务器的图像名称数组,您可以这样做:
<div style="height: 100px"><div :key="key" v-for="(img, key) in images" ><img :src="imageDir + key.substr(1)" class="" >
模板><脚本>导出默认{数据() {返回 {imageDir: "/your/path/to/images/",//你已经从目录结构中知道了这一点图片: {}}},安装(){this.importAll(require.context(this.imageDir, true,/.png$/))},方法: {导入所有(r){var imgs = {}r.keys().forEach(key => (imgs[key] = r(key)))this.images = imgs}}}
我不完全确定我的操作是否正确,但它从目录中返回图像并按预期显示它们.
I've created a simple app in Vue (using the Webpack template) that has a carousel in it. What I would like to do is loop through all of the images in static/images
to create that carousel. I know this is probably a dumb question, but how would I go about doing this? Do I need to perform a GET
request?
The reason I'm asking is because I'm going to hand this off to a client to be hosted on their server. They would like to be able to add additional images to the carousel themselves if needed.
Any help would be appreciated.
From this webpack documentation you can get all files in the directory or specific files based on a regex search pattern.
You could do something like:
var cache = {};
function importAll (r) {
r.keys().forEach(key => cache[key] = r(key));
}
importAll(require.context('../components/', true, /.js$/));
If you a need an array of image names from the server you could do this:
<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>
I am not entirely sure if I am doing it correctly but it return the images from the directory and displays them as expected.
这篇关于循环遍历 Vue.js 静态目录中的资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!