我们在开发过程中会发现,图片 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感知