ImagePreview.vue
<template>
<div>
<!-- 触发预览的图片 -->
<img :src="src" :alt="alt" class="preview-trigger" @click="openPreview" />
<!-- 图片预览模态框 -->
<div v-if="isPreviewOpen" class="preview-modal" @click="closePreview">
<div class="preview-content" @click.stop>
<!-- 控制按钮区域 -->
<div class="controls">
<button @click="zoomIn">放大</button>
<button @click="zoomOut">缩小</button>
<button @click="rotateClockwise">顺时针旋转</button>
<button @click="rotateCounterClockwise">逆时针旋转</button>
</div>
<!-- 图片预览区域 -->
<img :src="src" :alt="alt" class="preview-image" :style="{ transform: `scale(${scale}) rotate(${rotation}deg)` }" />
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'ImagePreview',
props: {
src: {
type: String,
required: true
},
alt: {
type: String,
default: 'Image'
}
},
setup(props) {
// 图片预览状态和变换状态
const isPreviewOpen = ref(false);
const scale = ref(1); // 初始缩放比例
const rotation = ref(0); // 初始旋转角度
// 打开预览
const openPreview = () => {
isPreviewOpen.value = true;
};
// 关闭预览
const closePreview = () => {
isPreviewOpen.value = false;
};
// 放大图片
const zoomIn = () => {
if (scale.value < 3) {
// 设置最大缩放比例
scale.value += 0.1;
}
};
// 缩小图片
const zoomOut = () => {
if (scale.value > 0.5) {
// 设置最小缩放比例
scale.value -= 0.1;
}
};
// 顺时针旋转图片
const rotateClockwise = () => {
rotation.value += 90;
};
// 逆时针旋转图片
const rotateCounterClockwise = () => {
rotation.value -= 90;
};
return {
isPreviewOpen,
scale,
rotation,
openPreview,
closePreview,
zoomIn,
zoomOut,
rotateClockwise,
rotateCounterClockwise,
src: props.src,
alt: props.alt
};
}
};
</script>
<style scoped>
.preview-trigger {
cursor: pointer;
max-width: 100%;
display: block;
margin: 0 auto;
}
.preview-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.preview-content {
position: relative;
padding: 20px;
background: #fff;
max-width: 90%;
max-height: 90%;
overflow: hidden;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
}
.preview-image {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
object-fit: contain;
transition: transform 0.3s ease;
}
.controls {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
.controls button {
background-color: rgba(255, 255, 255, 0.7);
border: none;
padding: 10px;
margin: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.controls button:hover {
background-color: rgba(255, 255, 255, 1);
}
</style>
使用组件
import ImagePreview from './ImagePreview .vue';
<ImagePreview :style="{ width: '200px', height: '200px' }" :src="imageSrc" :alt="imageAlt" />
效果
