vue怎么实现相册
Vue 实现相册功能
基础项目搭建
使用 Vue CLI 创建项目:
vue create photo-album
安装必要依赖(如需要图片懒加载):
npm install vue-lazyload
数据结构设计
相册数据通常以数组形式存储,每个图片对象包含标题、URL等属性:
data() {
return {
photos: [
{ id: 1, title: '风景1', url: '/images/photo1.jpg', thumbnail: '/thumbs/photo1.jpg' },
{ id: 2, title: '风景2', url: '/images/photo2.jpg', thumbnail: '/thumbs/photo2.jpg' }
],
currentPhoto: null
}
}
图片展示组件
创建可复用的图片卡片组件(PhotoCard.vue):
<template>
<div class="photo-card" @click="$emit('select', photo)">
<img v-lazy="photo.thumbnail" :alt="photo.title">
<h3>{{ photo.title }}</h3>
</div>
</template>
<script>
export default {
props: ['photo']
}
</script>
<style scoped>
.photo-card {
width: 200px;
cursor: pointer;
transition: transform 0.3s;
}
.photo-card:hover {
transform: scale(1.05);
}
</style>
相册主页面
实现网格布局和图片预览功能:
<template>
<div class="album-container">
<div class="photo-grid">
<PhotoCard
v-for="photo in photos"
:key="photo.id"
:photo="photo"
@select="showPreview"
/>
</div>
<div v-if="currentPhoto" class="preview-modal" @click.self="currentPhoto = null">
<img :src="currentPhoto.url" :alt="currentPhoto.title">
<button @click="currentPhoto = null">×</button>
</div>
</div>
</template>
<script>
import PhotoCard from './PhotoCard.vue'
export default {
components: { PhotoCard },
methods: {
showPreview(photo) {
this.currentPhoto = photo
}
}
}
</script>
<style>
.photo-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
padding: 20px;
}
.preview-modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.8);
display: flex;
align-items: center;
justify-content: center;
}
.preview-modal img {
max-height: 80vh;
max-width: 80vw;
}
</style>
进阶功能实现
添加图片分类筛选:
computed: {
filteredPhotos() {
return this.category
? this.photos.filter(p => p.category === this.category)
: this.photos
}
}
实现图片上传功能:
<input type="file" @change="handleUpload" multiple accept="image/*">
methods: {
handleUpload(e) {
const files = Array.from(e.target.files)
files.forEach(file => {
const reader = new FileReader()
reader.onload = (event) => {
this.photos.push({
id: Date.now(),
title: file.name,
url: event.target.result,
thumbnail: event.target.result
})
}
reader.readAsDataURL(file)
})
}
}
性能优化
使用懒加载和缩略图:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
loading: '/loading.gif',
attempt: 3
})
添加无限滚动加载:
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
this.loadMorePhotos()
}
})






