vue实现图册
Vue 实现图册功能
安装依赖
确保项目已安装 Vue 和必要的图片处理库,如 vue-image-lightbox 或自定义组件所需的依赖。
npm install vue-image-lightbox
基本图册结构
创建一个 Vue 组件,用于展示图片列表和点击放大功能。

<template>
<div class="gallery">
<div v-for="(image, index) in images" :key="index" class="gallery-item">
<img :src="image.thumbnail" @click="openLightbox(index)" />
</div>
<light-box
:images="images"
:showLightBox="showLightbox"
:currentIndex="currentImageIndex"
@close="closeLightbox"
></light-box>
</div>
</template>
数据与逻辑
定义图片数据和 Lightbox 控制逻辑。
<script>
import LightBox from 'vue-image-lightbox';
export default {
components: {
LightBox,
},
data() {
return {
images: [
{ thumbnail: 'path/to/thumbnail1.jpg', full: 'path/to/full1.jpg' },
{ thumbnail: 'path/to/thumbnail2.jpg', full: 'path/to/full2.jpg' },
],
showLightbox: false,
currentImageIndex: 0,
};
},
methods: {
openLightbox(index) {
this.currentImageIndex = index;
this.showLightbox = true;
},
closeLightbox() {
this.showLightbox = false;
},
},
};
</script>
样式优化
添加 CSS 美化图册布局和 Lightbox 效果。

<style>
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
padding: 16px;
}
.gallery-item img {
width: 100%;
height: auto;
cursor: pointer;
border-radius: 8px;
transition: transform 0.3s;
}
.gallery-item img:hover {
transform: scale(1.05);
}
</style>
自定义组件替代方案
若不使用第三方库,可通过自定义模态框实现类似功能。
<template>
<div class="custom-gallery">
<div v-for="(image, index) in images" :key="index" class="gallery-item">
<img :src="image.thumbnail" @click="openModal(index)" />
</div>
<div v-if="isModalOpen" class="modal" @click="closeModal">
<img :src="images[currentImageIndex].full" class="modal-content" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
images: [
{ thumbnail: 'path/to/thumbnail1.jpg', full: 'path/to/full1.jpg' },
{ thumbnail: 'path/to/thumbnail2.jpg', full: 'path/to/full2.jpg' },
],
isModalOpen: false,
currentImageIndex: 0,
};
},
methods: {
openModal(index) {
this.currentImageIndex = index;
this.isModalOpen = true;
},
closeModal() {
this.isModalOpen = false;
},
},
};
</script>
分页与懒加载
对于大量图片,可添加分页或懒加载优化性能。
data() {
return {
currentPage: 1,
pageSize: 12,
allImages: [...], // 所有图片数据
};
},
computed: {
images() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allImages.slice(start, end);
},
},
通过以上方法,可以灵活实现 Vue 图册功能,根据需求选择第三方库或自定义组件方案。






