vant-swipe自适应图片高度+图片预览
1.vant-swipe自适应图片高度
当轮播图的图片高度不相同时,如果不设置高度,van-swipe-item则会采取最高的图片的高度作为高度,则其他图片高度低于这个高度,则会底部空白,影响美观
解决办法:利用Swipe Props 的 height(滑块高度) 和change 事件 每次切换图片时,重新获取图片高度,赋值给滑块高度
//获取
async mounted(){
let res= await this.getImgSize(this.imgs[0])
this.height=res.height/(res.width/375)
},
methods:{
// 通过图片的url获取图片尺寸
getImgSize (url) {
return new Promise((resolve, reject) => {
let img = new Image()
img.src = url
img.onload = () => {
resolve({
width: img.width,
height: img.height
})
}
})
}
//swipe的切换监听事件
async onChange(index) {
let res= await this.getImgSize(this.imgs[index])
// 图片固定宽度100vw
this.height=res.height/(res.width/375)
},
}
2.图片预览
使用vant的 ImagePreview函数,需要用到swipe的autoplay,当autoplay=0时,停止播放;当图片进入预览时,关闭自动播放,结束预览时,跳到对应的图片(需要暂时关闭轮播动画,不然会一闪而过),开始自动播放
//预览
showImage(i){
// 预览关闭轮播图滚动
this.autoplay=0
ImagePreview({
images: this.imgs,
//开始的图片位置
startPosition: i,
overlayStyle:{
background: '#000'
},
//关闭预览图时-该图为轮播图起始图
onClose:res=> {
//轮播图的方法,跳到对应的图片
this.$refs.vantSwiper.swipeTo(res.index,{
immediate:true //关闭轮播切换效果
})
this.autoplay=2000
},
});
},
3.全部代码
<template>
<div class="swiper">
<van-swipe class="my-swipe" :autoplay="autoplay" indicator-color="white" :height="height" duration="1000" ref="vantSwiper" @change="onChange">
<van-swipe-item v-for="(item,i) in imgs" :key="i" >
<img :src="item" alt="" @click="showImage(i)">
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import { ImagePreview } from 'vant';
export default {
data(){
return{
imgs:[
require('@/assets/swiper/1.jpg'),
require('@/assets/swiper/2.jpg'),
require('@/assets/swiper/3.jpg'),
require('@/assets/swiper/4.jpg'),
require('@/assets/swiper/5.jpg')
],
autoplay:2000,
height:null
}
},
async mounted(){
let res= await this.getImgSize(this.imgs[0])
this.height=res.height/(res.width/375)
},
methods:{
async onChange(index) {
let res= await this.getImgSize(this.imgs[index])
// 图片固定宽度100vw
this.height=res.height/(res.width/375)
},
//预览
showImage(i){
// 预览关闭轮播图滚动
this.autoplay=0
ImagePreview({
images: this.imgs,
//开始的图片位置
startPosition: i,
overlayStyle:{
background: '#000'
},
//关闭预览图时-该图为轮播图起始图
onClose:res=> {
//轮播图的方法,跳到对应的图片
this.$refs.vantSwiper.swipeTo(res.index,{
immediate:true //关闭轮播切换效果
})
this.autoplay=2000
},
});
},
// 获取图片尺寸
getImgSize (url) {
return new Promise((resolve, reject) => {
let img = new Image()
img.src = url
img.onload = () => {
resolve({
width: img.width,
height: img.height
})
}
})
}
}
}
</script>
<style lang="less" scoped>
.van-swipe-item{
img{
width: 100%;
}
}
.my-swipe{
position: relative;
font-size: 0;
}
.custom-indicator {
position: absolute;
right: 5px;
bottom: 5px;
padding: 2px 5px;
font-size: 12px;
background: rgba(0, 0, 0, 0.1);
}
</style>