vue2项目简单使用PhotoSwipe实现移动端图片预览(支持放大、缩小、拖拽等手势操作)

321 阅读1分钟

一、实现效果和官网

image.png

官网地址:PhotoSwipe

二、使用版本

"vue": "^2.6.12",
"photoswipe": "^5.4.0"

三、安装

npm install photoswipe@5.4.0

四、组件封装

<template>
    <div :id="galleryID">
        <a :href="images" data-pswp-width="300" data-pswp-height="530" target="_blank" rel="noreferrer"
            style="color: #46a6ff;font-size: 14px;font-weight: 500;">
            查看单个图片
        </a>
    </div>
</template>

<script>
//引用路径,和官网文档不同,需注意
import PhotoSwipeLightbox from 'photoswipe/dist/photoswipe-lightbox.esm.js';
import 'photoswipe/dist/photoswipe.css';

export default {
  name: 'SimpleGallery',
  props: {
    galleryID: String,
    images: {
      type: [Array, Object, String],
      default: () => []
    }
  },
  data() {
    return {
    };
  },
  mounted() {
    if (!this.lightbox) {
      this.lightbox = new PhotoSwipeLightbox({
        gallery: '#' + this.$props.galleryID,
        children: 'a',
        pswpModule: () => import('photoswipe'),
      });
      this.lightbox.init();
    }
  },
  unmounted() {
    if (this.lightbox) {
      this.lightbox.destroy();
      this.lightbox = null;
    }
  },
};
</script>

五、调用组件

<template>
    <gallery-image :images="images" galleryID="photoswipe" />
</template>
<script>
import GalleryImage from "@/components/GalleryImage";
export default {
  components: {  GalleryImage },
  data() {
    return {
      images:'you_url',//你的图片地址
    }
  },
  ...
  }
</script>

六、参考

# 在vue中使用photoswipe插件(作者:1块腹肌))

# Image Gallery for Vue.js(官方文档)