微信小程序(uniapp) 图片懒加载组件封装

我们在开发过程中会发现,图片 image 在图片链接未返回时没有占位,导致我们的用户体验这个适合我们就需要进行组件封装,代码如下:

<template>
	<view class="ps-r" :class="imgClass" :style="{'width': imgWidth,'height': imgHeigth}">
		<view v-show="!finishLoadFlag" class="ps-a tp-0 lf-0 skeleton.animate bg-ea" :class="imgClass"
			:style="{'width': imgWidth,'height': imgHeigth}"></view>
		<image v-show='finishLoadFlag' :mode='mode' lazy-load :lazy-load-margin="0" :class="(finishLoadFlag ? '' : 'before-load ') + imgClass"
			:src="originalImage" @load='finishLoad'
			:style="{'width': imgWidth&&finishLoadFlag ? imgWidth:'','height': imgHeigth&&finishLoadFlag?imgHeigth:'' }" />
	</view>
</template>

<script lang="ts" setup>
	// 方法
	import utils from '@/utils/utils'
	import {
		defineProps,
		ref,
		toRefs
	} from 'vue';

	const props = defineProps({
		//默认图片
		defaultImage: String,
		//原始图片
		originalImage: String,
		width: {
			type: String,
		},
		height: {
			type: String,
		},
		//图片剪裁mode,同Image组件的mode
		mode: {
			type: String,
			default: 'widthFix'
		},
		imgClass: String,
		preview:{
			type: Boolean,
			default: false
		},
		imageList: Array // 图片预览集合
		
		
	})
	const imgWidth = ref('')
	const imgHeigth = ref('')
	
	imgWidth.value = props.width
	imgHeigth.value = props.height

	const {
		width,
		height
	} = toRefs(props)

	// 控制开关
	let finishLoadFlag = ref < Boolean > (false)

	function finishLoad(e: any) {
		if (!imgWidth.value) imgWidth.value = e.detail.imgWidth + 'rpx'
		if (!imgHeigth.value) imgHeigth.value = e.detail.imgHeigth + 'rpx'
	
		// 不能第一时间加载出图片,可进行异步切换 setTimeout
		finishLoadFlag.value = true 
	}
	
	// 图片预览
	function hanledImage(){
	if(!props.preview) return
		uni.previewImage({
		current: props.originalImage,
		urls:props.imageList || [props.originalImage]
	})
	}
</script>

<style lang="scss" scoped>
	.before-load {
		width: 0;
		height: 0;
		opacity: 0;
	}
</style>

注意:懒加载属性 lazy-load lazy-load-margin 封装在图片组件中,但是不能嵌套组件太多层,容易丢失page感知

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值