Vue中使用vue-photo-preview实现图片放大、分组查看并且遍历动态加载的所有图片,添加自定义属性(2021年更新)
1、安装vue-photo-previewnpm install vue-photo-preview --save2、注册和配置import preview from 'vue-photo-preview'import 'vue-photo-preview/dist/skin.css'let options = {fullscreenEl: false,}Vue.use(preview, opt
·
1、安装vue-photo-preview
npm install vue-photo-preview --save
2、注册和配置
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
let options = {
fullscreenEl: false,
}
Vue.use(preview, options)
Vue.use(preview)
3、在img标签中添加preview自定义属性。
<img src="xxx.jpg" large="xxx_2x.jpg" preview="1" preview-text="描述">
preview值相同为同组图片。preview-text为预览时下方描述文字。 img的src默认为缩略图,如不填写large,则展示src。若有large,则显示large大图。
4、上面为简单使用,option其实还有更多可配置项,例如:
let options = {
fullscreenEl: false, //控制是否显示右上角全屏按钮
closeEl: false, //控制是否显示右上角关闭按钮
tapToClose: true, //点击滑动区域应关闭图库
shareEl: false, //控制是否显示分享按钮
zoomEl: false, //控制是否显示放大缩小按钮
counterEl: false, //控制是否显示左上角图片数量按钮
tapToToggleControls: true, //点击应切换控件的可见性
clickToCloseNonZoomable: true, //点击图片应关闭图库,仅当图像小于视口的大小时
indexIndicatorSep: ' / '//图片数量的分隔符
}
更多option配置项,见:https://photoswipe.com/documentation/options.html
5、若img标签使用的是异步图片数据,需要在加载数据之后,加一句:
this.$previewRefresh();
这样刷新之后,vue-photo-preview预览效果才起效。
6、vue中对异步图片数据,进行批量添加preview属性。使用下面代码放入mounted中,在data中定义changValue = ‘’,设置定时,并且调用代码置于this.$nextTick中,否则使用document.querySelectorAll时,可能出现undefined的情况。
setTimeout(() => {
//修改数据
this.changValue = 1
//DOM还没更新
this.$nextTick(() => {
//DOM现在更新了
this.getImgList()
})
},1000)
7、在methods中添加以下方法,遍历#test中所有img图片,并且添加preview属性,可设置不同值区分不同分组。
getImgList() {
let x = document.querySelectorAll("#test img")
// console.log('x:', x )
let i
for (i = 0; i < x.length; i++) {
x[i].setAttribute("preview", "")
}
this.$previewRefresh()
},
更多推荐
已为社区贡献1条内容
所有评论(0)