viewImage.vue 1.45 KB
<template>
  <div v-show="showImage" class="image-viewer">
    <div class="image-container">
      <img :src="url" :style="imgStyle" @error="handleError">
      <i class="el-icon-close close-icon" @click="close"></i>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ViewImage',
  data() {
    return {
      url: '',
      showImage: false,
      imgWidth: 800,
      imgHeight: 800
    }
  },
  computed: {
    imgStyle() {
      return {
        width: `${this.imgWidth}px`,
        height: `${this.imgHeight}px`
      }
    }
  },
  methods: {
    open(url) {
      this.url = url
      this.showImage = true
      this.calculateSize(url)
    },
    close() {
      this.showImage = false
    },
    calculateSize(url) {
      const img = new Image()
      img.src = url
      img.onload = () => {
        const ratio = img.width / img.height
        this.imgWidth = 800
        this.imgHeight = 800 / ratio
      }
    },
    handleError() {
      this.url = '/img/noPhoto.jpg'
    }
  }
}
</script>

<style scoped>
.image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-container {
  position: relative;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.close-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 24px;
  color: #f56c6c;
  cursor: pointer;
}
</style>