<template>
<view class="easy-loadimage" :id="uid">
<image class="origin-img" :src="imageSrc" :mode="mode"
v-if="loadImg&&!isLoadError"
v-show="showImg"
:class="{'no-transition':!openTransition,'show-transition':showTransition&&openTransition}"
@load="handleImgLoad"
@error="handleImgError">
</image>
</view>
</template>
<script>
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
})
}
export default{
props:{
imageSrc:{
type: String,
},
mode:{
type: String,
},
scrollTop:{
type: Number,
},
loadingMode:{
type: String,
default:'looming-gray'
},
openTransition:{
type: Boolean,
default:true,
},
viewHeight:{
type:Number,
default() {
return uni.getSystemInfoSync().windowHeight;
}
}
},
watch:{
scrollTop(val){
this.onScroll(val)
}
},
data(){
return {
uid:'',
loadImg:false,
showImg:false,
isLoadError:false,
showTransition:false,
}
},
methods:{
init(){
this.uid = 'uid-' + generateUUID();
this.$nextTick(this.onScroll)
},
handleImgLoad(e){
this.showImg = true;
setTimeout(()=>{
this.showTransition = true
},50)
},
handleImgError(e){
this.isLoadError = true;
},
onScroll(scrollTop){
if(this.loadImg || this.isLoadError) return;
const id = this.uid
const query = uni.createSelectorQuery().in(this);
query.select('#'+id).boundingClientRect(data => {
if(!data) return;
if(data.top - this.viewHeight<0){
this.loadImg = true;
}
}).exec()
},
},
mounted() {
this.init()
}
}
</script>
<style scoped>
image{
will-change: transform
}
.easy-loadimage{
width: 100%;
height: 100%;
}
.origin-img{
width: 100%;
height: 100%;
}
</style>