vue实现相册功能
Vue 相册功能实现步骤
基础项目搭建
使用 Vue CLI 或 Vite 创建项目,安装必要依赖如 vue-router(如需页面跳转)和 axios(如需后端交互)。
npm create vue@latest vue-photo-album
cd vue-photo-album
npm install axios
图片数据管理
通过数组存储图片信息,每个对象包含 id, title, url 等属性。可本地存储或从 API 获取。

// 示例数据
const photos = [
{ id: 1, title: '风景1', url: '/images/photo1.jpg', desc: '山脉景色' },
{ id: 2, title: '风景2', url: '/images/photo2.jpg', desc: '湖泊风光' }
]
图片展示组件
创建 PhotoGallery.vue 组件,使用 v-for 循环渲染图片网格。
<template>
<div class="gallery">
<div v-for="photo in photos" :key="photo.id" class="photo-card">
<img :src="photo.url" :alt="photo.title" @click="openModal(photo)">
<h3>{{ photo.title }}</h3>
</div>
</div>
</template>
图片模态框组件
创建 PhotoModal.vue 实现大图预览,通过 v-if 控制显示状态。

<template>
<div class="modal" v-if="isOpen" @click.self="closeModal">
<div class="modal-content">
<img :src="currentPhoto.url" :alt="currentPhoto.title">
<button @click="closeModal">关闭</button>
</div>
</div>
</template>
样式设计
使用 CSS Grid 或 Flexbox 布局相册网格,添加过渡动画提升体验。
/* 网格布局示例 */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.photo-card img {
width: 100%;
height: 200px;
object-fit: cover;
cursor: pointer;
transition: transform 0.3s;
}
.photo-card img:hover {
transform: scale(1.03);
}
进阶功能实现
- 分类筛选:添加 computed 属性实现按类别过滤
computed: { filteredPhotos() { return this.category ? this.photos.filter(p => p.category === this.category) : this.photos } } - 懒加载:使用
Intersection Observer API或vue-lazyload插件 - 上传功能:通过
<input type="file">结合 FormData 实现 - 路由配置:为不同相册创建独立路由(如
/album/:id)
状态管理(可选)
对于复杂场景,可使用 Pinia 管理相册状态:
// stores/album.js
export const useAlbumStore = defineStore('album', {
state: () => ({
photos: [],
currentPhoto: null
}),
actions: {
async fetchPhotos() {
const res = await axios.get('/api/photos')
this.photos = res.data
}
}
})
性能优化
- 使用 WebP 格式图片减小体积
- 实现图片预加载
- 添加分页加载避免一次性请求过多数据
- 使用 CDN 加速图片资源
完整示例结构
src/
├── components/
│ ├── PhotoGallery.vue
│ ├── PhotoModal.vue
│ └── UploadForm.vue
├── stores/
│ └── album.js
├── views/
│ ├── AlbumsView.vue
│ └── AlbumDetail.vue
└── App.vue






