vue实现图集
Vue 实现图集功能
在 Vue 中实现图集功能可以通过多种方式完成,以下是常见的实现方法:
使用第三方库 vue-image-lightbox 是一个流行的 Vue 图集组件,支持图片预览、缩放和滑动。安装后可以直接在组件中使用:

npm install vue-image-lightbox --save
<template>
<light-box :images="images" ref="lightbox"></light-box>
</template>
<script>
import LightBox from 'vue-image-lightbox'
export default {
components: { LightBox },
data() {
return {
images: [
{ src: 'image1.jpg', caption: '图片1' },
{ src: 'image2.jpg', caption: '图片2' }
]
}
}
}
</script>
自定义实现 创建一个简单的图集组件:

<template>
<div class="gallery">
<div v-for="(img, index) in images" :key="index" @click="openLightbox(index)">
<img :src="img.thumbnail" :alt="img.alt">
</div>
<div v-if="showLightbox" class="lightbox" @click.self="closeLightbox">
<img :src="currentImage.src" :alt="currentImage.alt">
<button @click="prevImage">上一张</button>
<button @click="nextImage">下一张</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
images: [...],
showLightbox: false,
currentIndex: 0
}
},
computed: {
currentImage() {
return this.images[this.currentIndex]
}
},
methods: {
openLightbox(index) {
this.currentIndex = index
this.showLightbox = true
},
closeLightbox() {
this.showLightbox = false
},
prevImage() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
},
nextImage() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
}
}
}
</script>
<style>
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 10px;
}
.lightbox {
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;
}
</style>
性能优化建议 对于大型图集,考虑使用懒加载技术。vue-lazyload 可以帮助延迟加载图片:
npm install vue-lazyload
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
loading: 'loading.gif',
attempt: 1
})
<img v-lazy="image.src" :alt="image.alt">
移动端适配 添加触摸事件支持可以实现移动端滑动切换:
<div class="lightbox"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd">
methods: {
handleTouchStart(e) {
this.touchStartX = e.touches[0].clientX
},
handleTouchMove(e) {
this.touchEndX = e.touches[0].clientX
},
handleTouchEnd() {
if (this.touchStartX - this.touchEndX > 50) {
this.nextImage()
}
if (this.touchEndX - this.touchStartX > 50) {
this.prevImage()
}
}
}






