vue实现多个图片预览
Vue 实现多图片预览功能
使用第三方库(推荐)
安装 viewerjs 或 vue-photo-preview 这类专门处理图片预览的库。
npm install viewerjs
在组件中引入并使用:
import Viewer from 'viewerjs'
import 'viewerjs/dist/viewer.css'
export default {
mounted() {
new Viewer(this.$refs.gallery)
}
}
模板部分:
<div ref="gallery">
<img v-for="(img, index) in images" :key="index" :src="img" width="100">
</div>
自定义模态框实现
创建一个图片预览组件:

<template>
<div class="preview-container" v-if="show">
<div class="preview-overlay" @click="close"></div>
<div class="preview-content">
<img :src="currentImage" @click.stop>
<button @click="prev">上一张</button>
<button @click="next">下一张</button>
<button @click="close">关闭</button>
</div>
</div>
</template>
<script>
export default {
props: ['images'],
data() {
return {
show: false,
currentIndex: 0
}
},
computed: {
currentImage() {
return this.images[this.currentIndex]
}
},
methods: {
open(index) {
this.currentIndex = index
this.show = true
},
close() {
this.show = false
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
}
}
}
</script>
使用 Element UI 组件
如果项目使用 Element UI,可以直接使用其图片预览组件:
<template>
<el-image
v-for="(img, index) in images"
:key="index"
:src="img"
:preview-src-list="images"
></el-image>
</template>
<script>
export default {
data() {
return {
images: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
]
}
}
}
</script>
移动端优化方案
对于移动端,建议添加手势支持:
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchEnd(e) {
const endX = e.changedTouches[0].clientX
if (this.startX - endX > 50) {
this.next()
} else if (endX - this.startX > 50) {
this.prev()
}
}
}
模板添加触摸事件:

<img
:src="currentImage"
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
>
性能优化建议
对于大量图片,使用懒加载技术:
<img
v-for="(img, index) in images"
:key="index"
v-lazy="img"
@click="open(index)"
>
安装 vue-lazyload:
npm install vue-lazyload
在 main.js 中配置:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
loading: 'loading.gif',
attempt: 1
})






