微信小程序的图片预览兼容性处理

在开发时发现,使用uniapp的预览图片方法(uni.previewImage)在微信小程序上进行图片预览时,会发现预览窗口黑屏,没法正常显示图片。在网上搜索资料发现需要做以下设置

<view class="list-item" v-for="(item,idx) in list" :key="idx">
	<u-image @click.native.prevent="previewImage($event,idx)" :data-src="item" mode="aspectFit" width="200rpx" height="200rpx" border-radius="24rpx" :src="item">
	</u-image>
</view>

在绑定点击事件时,需要传递两个值,一个是事件本身属性,一个是图片数组的索引值。需要注意的是在图片组件需要传一个自定义参数:data-src="item"这个参数是单张图片的地址。

previewImage(e, idx) {
	// #ifdef MP-WEIXIN
	const current = e.target.dataset.src
	uni.previewImage({
		urls: this.picList,
		current: current
	})
	// #endif
	// #ifndef MP-WEIXIN
	uni.previewImage({
		urls: this.picList,
		current: idx,
	})
	// #endif
}

在预览图片的方法里,根据运行环境是否为微信小程序进行判断,分别给current传递不同的参数,这样就能在微信小程序中正确的显示图片预览了。

Last updated

Was this helpful?