vue图片预览怎么实现
使用 vue-image-lightbox 插件
安装插件依赖:
npm install vue-image-lightbox --save
在组件中引入并使用:
<template>
<button @click="showLightbox">预览图片</button>
<light-box
:images="images"
:showLightBox="show"
@onClose="show = false"
/>
</template>
<script>
import LightBox from 'vue-image-lightbox'
export default {
components: { LightBox },
data() {
return {
show: false,
images: [
{ src: 'image1.jpg', caption: '图片1' },
{ src: 'image2.jpg', caption: '图片2' }
]
}
},
methods: {
showLightbox() {
this.show = true
}
}
}
</script>
使用 v-viewer 插件
安装插件:
npm install v-viewer
全局注册:
import VueViewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
Vue.use(VueViewer)
组件中使用:
<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.$viewer.defaultViewer()
}
}
</script>
自定义实现图片预览
创建遮罩层组件:
<template>
<div class="preview-mask" v-if="visible" @click.self="close">
<img :src="currentImage" class="preview-image">
<button @click="close" class="close-btn">×</button>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
currentImage: String
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style>
.preview-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.preview-image {
max-width: 90%;
max-height: 90%;
}
.close-btn {
position: absolute;
top: 20px;
right: 20px;
color: white;
font-size: 30px;
background: none;
border: none;
cursor: pointer;
}
</style>
使用 Element UI 的 Image 组件
安装 Element UI:
npm install element-ui
引入组件:
<template>
<el-image
:src="imageUrl"
:preview-src-list="[imageUrl]"
fit="cover"
>
</el-image>
</template>
<script>
import { Image } from 'element-ui'
export default {
components: { ElImage: Image },
data() {
return {
imageUrl: 'image.jpg'
}
}
}
</script>






