vue图片预览组件实现
基于第三方库的实现(推荐)
使用成熟的第三方库如 viewerjs 或 vue-viewer 可快速实现功能完整的图片预览。
安装依赖:
npm install v-viewer
组件封装示例:
<template>
<div>
<img v-for="src in images" :src="src" :key="src" @click="show(src)">
</div>
</template>
<script>
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
export default {
data() {
return {
images: [
'image1.jpg',
'image2.jpg'
]
}
},
methods: {
show(src) {
const viewer = this.$viewerApi({
images: this.images,
options: {
initialViewIndex: this.images.indexOf(src),
toolbar: {
zoomIn: 1,
zoomOut: 1,
rotateLeft: 1,
rotateRight: 1
}
}
})
}
}
}
</script>
自定义基础实现
通过CSS和Vue指令实现简易预览功能。
<template>
<div class="preview-container">
<img
v-for="img in imgList"
:src="img"
@click="openPreview(img)"
class="thumbnail">
<div v-if="showModal" class="modal">
<span class="close" @click="closePreview">×</span>
<img :src="currentImg" class="modal-content">
</div>
</div>
</template>
<script>
export default {
data() {
return {
imgList: ['image1.jpg', 'image2.jpg'],
showModal: false,
currentImg: ''
}
},
methods: {
openPreview(img) {
this.currentImg = img
this.showModal = true
},
closePreview() {
this.showModal = false
}
}
}
</script>
<style>
.thumbnail {
width: 100px;
cursor: pointer;
}
.modal {
position: fixed;
z-index: 999;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.9);
}
.modal-content {
display: block;
margin: auto;
max-width: 80%;
max-height: 80%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
cursor: pointer;
}
</style>
功能增强方案
-
添加手势支持
// 在mounted中添加手势监听 this.$el.addEventListener('swipeleft', this.nextImage) this.$el.addEventListener('swiperight', this.prevImage) -
图片懒加载
<img v-lazy="img.src" @click="previewImage"> -
缩放控制
// 添加滚轮事件监听 window.addEventListener('wheel', this.handleZoom, { passive: false })
methods: { handleZoom(e) { if (!this.showModal) return e.preventDefault() const scale = e.deltaY > 0 ? 0.9 : 1.1 this.currentScale = Math.max(0.5, Math.min(3, this.currentScale * scale)) } }

### 移动端优化要点
1. 添加`touch-action: none`样式禁用默认手势
2. 实现双指缩放手势检测
3. 使用`transform: scale()`实现流畅的缩放动画
4. 添加loading状态处理大图加载
### 性能优化建议
1. 使用WebP格式图片减少体积
2. 实现图片预加载
3. 虚拟滚动处理大量图片
4. 添加缓存机制避免重复请求
以上方案可根据实际需求组合使用,第三方库适合快速实现完整功能,自定义方案则更灵活可控。






