使用vue实现图片预览
使用 Vue 实现图片预览
使用原生 HTML5 和 Vue 实现
通过 v-for 循环渲染图片列表,点击图片时显示大图预览。
<template>
<div>
<div class="image-list">
<img
v-for="(image, index) in images"
:key="index"
:src="image.thumbnail"
@click="showPreview(image.url)"
>
</div>
<div class="preview-modal" v-if="previewImage" @click="previewImage = null">
<img :src="previewImage" class="preview-image">
</div>
</div>
</template>
<script>
export default {
data() {
return {
images: [
{ thumbnail: 'thumb1.jpg', url: 'large1.jpg' },
{ thumbnail: 'thumb2.jpg', url: 'large2.jpg' }
],
previewImage: null
}
},
methods: {
showPreview(url) {
this.previewImage = url
}
}
}
</script>
<style>
.preview-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.preview-image {
max-width: 90%;
max-height: 90%;
}
.image-list img {
width: 100px;
height: 100px;
margin: 10px;
cursor: pointer;
}
</style>
使用第三方库 vue-image-lightbox
安装 vue-image-lightbox 可以快速实现功能丰富的图片预览。
npm install vue-image-lightbox --save
在组件中使用:
<template>
<div>
<button @click="showLightbox = true">Open Lightbox</button>
<light-box
:images="images"
:show-light-box="showLightbox"
@on-close="showLightbox = false"
/>
</div>
</template>
<script>
import LightBox from 'vue-image-lightbox'
export default {
components: {
LightBox
},
data() {
return {
showLightbox: false,
images: [
{ src: 'image1.jpg', caption: 'Image 1' },
{ src: 'image2.jpg', caption: 'Image 2' }
]
}
}
}
</script>
使用 Viewer.js 实现高级功能
Viewer.js 提供缩放、旋转等高级功能。
安装依赖:
npm install v-viewer
在 main.js 中全局注册:
import Vue from 'vue'
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
Vue.use(Viewer)
在组件中使用:
<template>
<div class="images">
<img v-for="src in images" :src="src" :key="src">
</div>
</template>
<script>
export default {
data() {
return {
images: ['image1.jpg', 'image2.jpg']
}
},
mounted() {
this.$viewerApi({
images: this.images
})
}
}
</script>
自定义图片预览组件
创建可复用的图片预览组件:
<!-- ImagePreview.vue -->
<template>
<div class="image-preview">
<img :src="src" @click="open">
<div class="modal" v-if="visible" @click="close">
<img :src="src">
</div>
</div>
</template>
<script>
export default {
props: ['src'],
data() {
return {
visible: false
}
},
methods: {
open() {
this.visible = true
document.body.style.overflow = 'hidden'
},
close() {
this.visible = false
document.body.style.overflow = ''
}
}
}
</script>
<style scoped>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal img {
max-width: 90%;
max-height: 90%;
}
</style>
使用时:

<template>
<div>
<image-preview src="image.jpg"></image-preview>
</div>
</template>
<script>
import ImagePreview from './ImagePreview.vue'
export default {
components: {
ImagePreview
}
}
</script>






