uni-app 通过uni.previewImage预览图片时,右滑切换图片后切换设备横竖屏,预览图片变回current传入的初始索引图片
uni-app 通过uni.previewImage预览图片时,右滑切换图片后切换设备横竖屏,预览图片变回current传入的初始索引图片
1 回复
在使用 uni.previewImage
预览图片时,如果遇到右滑切换图片后切换设备横竖屏,预览图片变回 current
传入的初始索引图片的问题,这可能是由于横竖屏切换时,页面重新渲染导致的。
解决方案
为了在横竖屏切换时保持当前预览的图片索引,可以通过以下步骤来实现:
- 监听横竖屏切换事件:使用
uni.onWindowResize
监听屏幕尺寸变化事件。 - 保存当前预览的图片索引:在切换图片时,保存当前预览的图片索引。
- 在横竖屏切换时重新调用
uni.previewImage
:在横竖屏切换后,重新调用uni.previewImage
并传入保存的当前索引。
示例代码
export default {
data() {
return {
imageList: [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
],
currentIndex: 0 // 当前预览的图片索引
};
},
methods: {
previewImage(index) {
this.currentIndex = index;
uni.previewImage({
current: this.currentIndex,
urls: this.imageList,
success: () => {
// 监听屏幕尺寸变化
uni.onWindowResize((res) => {
this.handleScreenRotate();
});
}
});
},
handleScreenRotate() {
// 重新调用预览图片方法,传入当前索引
uni.previewImage({
current: this.currentIndex,
urls: this.imageList
});
}
}
};