最近遇到的一个可以放大预览图片的需求,类似于微信公众号文章中的图片可以点击放大查看,左右滑动查看上一张、下一张。
在网站找到了photoswipe
插件(官网),记录一下使用笔记。
使用版本
"vue": "^2.6.12",
"photoswipe": "^5.4.0"
封装组件
接收一个数组,需要有图片的src,width,height信息
<template>
<div :id="galleryID">
<a
v-for="(image, key) in images"
:key="key"
:href="image.largeURL"
:data-pswp-width="image.width"
:data-pswp-height="image.height"
target="_blank"
rel="noreferrer"
>
<img :src="image.largeURL" alt="" />
</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: Array
},
data() {
return {
lightbox: null
};
},
methods: {
//点击图片时初始化
openImg(src) {
if (!this.lightbox) {
this.lightbox = new PhotoSwipeLightbox({
gallery: '#' + this.$props.galleryID,
children: 'a',
loop: false,
imageClickAction: 'close', //PC端单击关闭
tapAction: 'close', //手机端单击关闭
showHideAnimationType: 'fade', //出现动画
pswpModule: () => import('photoswipe')
});
this.lightbox.init();
}
let index = this.images.findIndex(item => item.largeURL == src);
if (index != -1) {
this.lightbox.loadAndOpen(index, {
gallery: document.querySelector(`#${this.galleryID}`)
});
}
},
close(){
this.lightbox && this.lightbox.pswp.close();
}
}
};
</script>
使用
- 把所有图片整理到一个数组里,需要获取图片的 默认宽高
<template>
<div>
<div ref="content-box" @click="handleClick">
<p>其他内容...</p>
<img src="https://placekitten.com/600/600" width="600" height="600" />
<p>其他内容...</p>
</div>
<SimpleGallery v-show="false" ref="SimpleGallery" galleryID="my-test-gallery" :images="images" />
</div>
</template>
<script>
import SimpleGallery from '../common/SimpleGallery.vue';
export default {
components: { SimpleGallery },
data() {
return {
images: []
};
},
mounted(){
//获取img,整理组件所需参数
this.initSimpleGallery()
},
//退出页面时,关闭预览
beforeDestroy() {
if (this.$refs.SimpleGallery.lightbox && this.$refs.SimpleGallery.lightbox.pswp) {
if (this.$refs.SimpleGallery.lightbox.pswp.isOpen == true) {
this.$refs.SimpleGallery.close();
}
}
},
methods: {
handleClick(e) {
if (e.target.tagName == 'IMG' && e.target.src) {
this.$refs.SimpleGallery.openImg(e.target.src);
}
},
//获取元素内所有img
initSimpleGallery() {
let imgs = this.$refs['content-box'].querySelectorAll('img[src][height][width]');
imgs.forEach(ele => {
this.images.push({ largeURL: ele.src, width: 0, height: 0 });
});
this.getImageSize();
},
//获取图片的宽高
getImageSize() {
this.images.forEach((ele, index) => {
let image = new Image();
image.src = ele.largeURL;
image.onload = () => {
this.images[index].width = image.width;
this.images[index].height = image.height;
};
image.onerror = function() {
new Error('img load error');
};
});
}
}
};
</script>
完~