vue实现图库页面
Vue 实现图库页面
数据准备与结构设计
使用 Vue 的 data 或 setup(Composition API)定义图片数据数组,每张图片包含 id、src、title 等字段。示例数据结构:
data() {
return {
images: [
{ id: 1, src: 'path/to/image1.jpg', title: '示例1' },
{ id: 2, src: 'path/to/image2.jpg', title: '示例2' }
]
}
}
图片列表渲染
通过 v-for 循环渲染图片缩略图,使用 <img> 标签绑定 src 和点击事件:
<div class="gallery">
<div v-for="image in images" :key="image.id" @click="openModal(image)">
<img :src="image.src" :alt="image.title">
<p>{{ image.title }}</p>
</div>
</div>
模态框实现
通过 v-show 或 v-if 控制模态框显示,展示大图及详细信息:

<div class="modal" v-show="selectedImage">
<img :src="selectedImage.src" :alt="selectedImage.title">
<button @click="closeModal">关闭</button>
</div>
对应方法:
methods: {
openModal(image) {
this.selectedImage = image;
},
closeModal() {
this.selectedImage = null;
}
}
样式优化
添加 CSS 实现网格布局和过渡动画:

.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
}
懒加载优化
使用 Intersection Observer 或 vue-lazyload 插件实现图片懒加载:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
loading: 'placeholder-image.jpg'
})
模板中替换 src 为 v-lazy:
<img v-lazy="image.src" :alt="image.title">
分页加载
结合 v-infinite-scroll 或自定义滚动事件实现分页:
loadMore() {
if (this.isLoading) return;
this.isLoading = true;
fetchNextPage().then(newImages => {
this.images.push(...newImages);
this.isLoading = false;
});
}






