vue3 + antd实现简单的图片点开可以缩小放大查看

发布于:2025-08-19 ⋅ 阅读:(22) ⋅ 点赞:(0)

通过ref传参src打开弹窗

点击图片放大


<img
              v-if="getFileType(record[column.key]) === '图片'"
              :src="`${defaultBaseURL + record[column.key]}`"
              class="img-style"
              @click="handleImgClick(`${defaultBaseURL + record[column.key]}`)"
            />



// 点击打开图片
function handleImgClick(imgUrl: string) {
  showImgRef.value.openModel(imgUrl);
}

// 引用图片展示组件
<ModelShowImg ref="showImgRef" />

图片展示组件代码

<script lang="ts" setup>
import { ref } from 'vue';

import { CloseOutlined } from '@ant-design/icons-vue';

const open = ref(false);
const showImg = ref('');
const x = ref(0);
const y = ref(0);
const startx = ref(0);
const starty = ref(0);
const endx = ref(0);
const endy = ref(0);
const height = ref(800);
function closeImg() {
  showImg.value = '';
  open.value = false;
  x.value = 0;
  y.value = 0;
  startx.value = 0;
  starty.value = 0;
  endx.value = 0;
  endy.value = 0;
  height.value = 800;
}
function changeImg(e: any) {
  if (e.deltaY < 0) {
    height.value += 80;
  } else {
    if (height.value > 80) {
      height.value -= 80;
    }
  }
}
function mousedown(e: any) {
  startx.value = e.pageX;
  starty.value = e.pageY;
  document.addEventListener('mousemove', mousemove);
  document.querySelector('#imgId')?.addEventListener('mouseup', mouseup);
}
function mousemove(e: any) {
  x.value = e.pageX - startx.value + endx.value;
  y.value = e.pageY - starty.value + endy.value;
}
function mouseup() {
  // 解除绑定mousemove
  document.removeEventListener('mousemove', mousemove, false);
  endx.value = x.value;
  endy.value = y.value;
}
function openModel(imgUrl: string) {
  showImg.value = imgUrl;
  open.value = true;
}
// 暴露方法给父组件调用
defineExpose({ openModel });
</script>
<template>
  <a-modal
    v-model:open="open"
    :centered="true"
    :closable="false"
    :footer="null"
    :mask-closable="false"
    width="100%"
    wrap-class-name="dialogModalBox"
    @cancel="closeImg"
  >
    <img
      v-if="showImg"
      id="imgId"
      :src="showImg"
      :style="{ transform: `translate(${x}px,${y}px)`, height: `${height}px` }"
      draggable="false"
      @mousedown="mousedown($event)"
      @mousewheel="changeImg($event)"
    />
    <CloseOutlined class="close" @click="closeImg" />
  </a-modal>
</template>
<style lang="less">
.dialogModalBox {
  .ant-modal .ant-modal-content {
    padding: 0;
    background-color: rgba(0, 0, 0, 0);
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    height: 100vh;
  }
}
.close {
  position: fixed;
  right: 30px;
  top: 30px;
  color: white;
  font-size: 32px;
}
</style>

效果:点击图片按下可以拖拽,滚轮可以放大缩小图片,右上角X按钮关闭


网站公告

今日签到

点亮在社区的每一天
去签到