vue实现每组多个图片
Vue 实现每组多个图片的展示
在 Vue 中展示每组多个图片可以通过多种方式实现,常见的方法包括使用 v-for 循环渲染图片组、结合 CSS 布局或第三方组件库。
使用 v-for 循环渲染图片组
通过 v-for 可以动态渲染多组图片,每组包含多个图片。假设数据是一个嵌套数组,每组包含多个图片 URL。
<template>
<div class="image-groups">
<div v-for="(group, groupIndex) in imageGroups" :key="groupIndex" class="group">
<img
v-for="(image, imageIndex) in group"
:key="imageIndex"
:src="image"
class="image"
/>
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageGroups: [
["image1.jpg", "image2.jpg", "image3.jpg"],
["image4.jpg", "image5.jpg", "image6.jpg"],
]
};
}
};
</script>
<style>
.image-groups {
display: flex;
flex-direction: column;
gap: 20px;
}
.group {
display: flex;
gap: 10px;
}
.image {
width: 100px;
height: 100px;
object-fit: cover;
}
</style>
使用 CSS Grid 布局
如果需要更灵活的布局,可以使用 CSS Grid 控制每组图片的排列方式。
<template>
<div class="image-groups-grid">
<div v-for="(group, groupIndex) in imageGroups" :key="groupIndex" class="group-grid">
<img
v-for="(image, imageIndex) in group"
:key="imageIndex"
:src="image"
class="image-grid"
/>
</div>
</div>
</template>
<style>
.image-groups-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
}
.group-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.image-grid {
width: 100%;
height: 100px;
object-fit: cover;
}
</style>
使用第三方组件库(如 Element UI)
如果项目中使用 Element UI,可以利用其 el-row 和 el-col 组件实现分组图片展示。
<template>
<el-row :gutter="20" class="image-groups-element">
<el-col v-for="(group, groupIndex) in imageGroups" :key="groupIndex" :span="24">
<el-row :gutter="10">
<el-col v-for="(image, imageIndex) in group" :key="imageIndex" :span="8">
<img :src="image" class="image-element" />
</el-col>
</el-row>
</el-col>
</el-row>
</template>
<style>
.image-groups-element {
margin-bottom: 20px;
}
.image-element {
width: 100%;
height: 100px;
object-fit: cover;
}
</style>
动态加载图片组
如果图片数据需要从接口获取,可以通过异步加载的方式实现。
<template>
<div v-if="loading">Loading...</div>
<div v-else class="image-groups">
<div v-for="(group, groupIndex) in imageGroups" :key="groupIndex" class="group">
<img
v-for="(image, imageIndex) in group"
:key="imageIndex"
:src="image.url"
class="image"
/>
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageGroups: [],
loading: true
};
},
async created() {
try {
const response = await fetch('https://api.example.com/images');
this.imageGroups = await response.json();
this.loading = false;
} catch (error) {
console.error(error);
this.loading = false;
}
}
};
</script>
响应式图片组
为了适应不同屏幕尺寸,可以使用响应式设计调整图片组的显示方式。
.group {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.image {
width: calc(33.333% - 10px);
height: auto;
}
@media (max-width: 768px) {
.image {
width: calc(50% - 10px);
}
}
@media (max-width: 480px) {
.image {
width: 100%;
}
}
以上方法可以根据具体需求选择或组合使用,灵活实现每组多个图片的展示效果。







