需求描述:
1、图片预览时,通常需要知道,当前预览的是第几张,总共有多少张图片;
2、当用户左右滑动切换预览图片时,当前预览索引需要随着进行切换。

下面简单介绍下实现过程:
1、在图片列表页点击预览图片时,把图片Id作为参数传递过去
javascript
<navigator :url="'/pages/preview/preview?id='+item._id" class="item" v-for="item in classifyList" :key="item._id">
2、在预览详情页获取传递过来的id,通过前面的学习可知,可使用onLoad函数获取
javascript
//分页图片列表,前面笔记有记录怎么获取,这里略
const classList = ref([])
//当前图片的id
const currentId = ref(null)
//当前图片的索引,默认为第1张
const currentIndex = ref(0)
//使用onLoad函数,通过id获取当前索引
//如果当前id等于分类列表指定项的id,则该项的索引则为当前图片的索引
onLoad((e)=>{
currentId.value = e.id
currentIndex.value = classList.value.findIndex(item=>item._id == currentId.value)
console.log("index:"+currentIndex)
})
在模板层使用上面代码获取到的索引,由于索引从0开始,当前查看是第几张图片则需要索引加1,预览总数为分类列表数组的长度
html
<view class="count">{{currentIndex+1}} / {{classList.length}} </view>
最后再来实现图片切换时,索引页的切换
html
<swiper circular :current="currentIndex" @change="swiperChange">
在swiper中当前图片所在的索引即为上面JS获得的currentIndex,当滑动图片时,通过change事件来改变当前索引
javascript
const swiperChange =(e) =>{
currentIndex.value = e.detail.current;
}