主题
vue遍历图片文件夹
本文将教你如何使用 Vue 3 动态从指定的图片文件夹获取图片
nginx配置
nginx
location /images {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' '*';
# OPTIONS 直接返回204
if ($request_method = 'OPTIONS') {
return 204;
}
alias /web/images;
autoindex on; # 关键! 启用目录索引
expires 3d; # 缓存3天
}
脚本部分
js
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
const imageUrls = ref<string[]>([]);
onMounted(async () => {
try {
const uri = 'https://..域名../images/';
// 假设后端提供了一个返回图片 URL 列表的接口
const response = await axios.get(uri);
const html = response.data;
// 使用正则表达式提取图片 URL
const urls = Array.from(html.matchAll(/<a href="([^"]+\.(jpg|jpeg|png|gif|bmp))">/gi))
.map(match => `${uri}${match[1]}`);
// 更新图片 URL 列表
imageUrls.value = urls;
} catch (error) {
console.error('Failed to fetch image URLs:', error);
}
});
</script>
因为nginx返回的html,所以需要使用正则表达式提取图片 URL。
显示模板部分
html
<div class="masonry-grid">
<div class="item" v-for="url in imageUrls" :key="url">
<img :src="url" loading="lazy"> <!-- 支持图片懒加载 -->
</div>
</div>
这里使用了瀑布流布局, 可以参考瀑布流布局