u-image

183 阅读1分钟
<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>
// 生成全局唯一id
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){
            // console.log('success');
            this.showImg = true;
            // this.$nextTick(function(){
            //     this.showTransition = true
            // })
            setTimeout(()=>{
                this.showTransition = true
            },50)
        },
        handleImgError(e){
            // console.log('fail');
            this.isLoadError = true;
        },
        onScroll(scrollTop){
            // 加载ing时才执行滚动监听判断是否可加载
            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>
    /* 官方优化图片tips */
    image{
        will-change: transform
    } 
    .easy-loadimage{
        width: 100%;
        height: 100%;
    }
    .origin-img{
         width: 100%;
        height: 100%;
    }
</style>