超简单☞vue-photo-preview

2020-08-09  本文已影响0人  小学生的博客

忙?懒:懒。
好久没有更新东西了。忙里偷闲,记录点东西吧。

项目中需要图片预览功能。
首先想到的是,使用element的Dialog展示,但是需要改弹窗的样式,另外图片的宽度不固定,高度也不固定,这样做出来的效果比较难看。放弃了el-dialog。
然后想着网上有什么开源的组件,拿来直接用。总比自己造轮子强吧。看了 vue-photo-viewer之类的,基本上都是轮播形式,并且不能阴式的调用。不能满足需求。放弃。

自己动手丰衣足食,还是自己搞吧。

总结下常见的展示样式,然后自己搞了个,样式如下:


image.png

首先封装:

<template>
  <div class="photo_preview" v-if="dialogVisible">
    <div class="photo_preview_dialog">
      <div class="preview_header">
        <el-button type="text" @click="dialogClose(false)">关 闭</el-button>
      </div>
      <div class="preview_body" :style="{height:warpHeight+'px'}" @click="dialogClose(false)">
        <img :src="src" class="img"
             :style="mouseStyle"
             alt="" @click.stop="handleMouse">
      </div>
    </div>
  </div>
</template>
<script>

  export default {
    name: '',
    props: {
      src: {
        type: String,
        default: ''
      },
      visible: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        dialogVisible: false,
        warpHeight: '',
        mouseStyle: {
          cursor: 'zoom-in',
          height: '80%'
        },
        toogle: false
      }
    },
    created () {
      this.dialogVisible = this.visible
    },
    watch: {
      visible (val, oldval) {
        this.dialogVisible = val
        this.warpHeight = document.body.clientHeight - 100
      }
    },
    methods: {
      dialogClose (value) {
        this.$emit('close', value)
        Object.assign(this.$data, this.$options.data())
      },
      handleMouse () {
        let cursor = this.toogle ? 'zoom-in' : 'zoom-out'
        let height = this.toogle ? '80%' : '100%'
        this.toogle = !this.toogle

        this.mouseStyle = {
          cursor: cursor,
          height: height
        }
      }
    }
  }

</script>

<style lang="scss" scoped>
  .photo_preview {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.9) !important;
    z-index: 999999;
    overflow: hidden;

    .photo_preview_dialog {
      position: relative;
      width: 100%;
      margin: 0 auto;
      height: 100%;

      .preview_header {
        height: 50px;
        padding: 0 20px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .el-button {
          color: #ffffff;
        }
      }

      .preview_body {
        position: relative;
        margin: 0 auto;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        .img {
          height: 100%;
          width: auto;
          display: block;
        }
      }
    }

  }
</style>

调用 this.showDialog=true :


    <f-photo-preview 
      :src="imgUrl" 
      :visible="showDialog" 
      @close="e => showDialog = e">
    </f-photo-preview>

暂时功能可以满足放大缩小图片。

上一篇下一篇

猜你喜欢

热点阅读