uniapp 小程序懒加载(自己封装组件)

前言

用uniapp 开发小程序,商品的列表页面,当然需要用到懒加载了,

当然我写的这个拉加载 只是针对效果图,但是也很炫酷,适合列表哦!! 

啊哈

原理其实就是用了 

 @load 和error 的2个方法来判断是否加载完全 和出错

<image class="real-image" @load="onLoaded" :src="realSrc" :mode="mode" @error="handleImgError"></image>

然后就是代码周小程序期逻辑了:

我封装了成了了组件,还是看代码吧,啊哈

uniapp 小程序懒加载(自己封装组件)

LOOK:

<!-- 懒加载的loadImage --><template> <!-- mode="widthFix" --> <view class="lazy-image" :style="{‘width‘: (width? width+‘rpx‘:‘100%‘)}"> <image class="real-image" @load="onLoaded" :src="realSrc" :mode="mode" @error="handleImgError"></image> <view :class="loaded?‘loaded‘:‘‘" v-if="!isLoadError"> <image :src="placeholdSrc" mode="aspectFit"></image> </view> <view :class="loaded?‘loaded‘:‘‘" v-if="isLoadError"> <image :src="failSrc" mode="aspectFit"></image> </view> </view></template><script> export default { props:{ placeholdSrc:{ type:String, default:"../static/easyLoadimage/loading.gif" //loading.gif loadfail.png }, failSrc:{ type:String, default:"../static/easyLoadimage/loadfail.png" // }, realSrc:{ type:String, default:"" }, mode:{ type:String, default:"widthFix" }, width:{ type:String, default:"" } }, data(){ return { loaded:false, isLoadError:false, showImg:false, } }, methods:{ onLoaded(e){ this.loaded = true; this.showImg = true }, // 加载错误 handleImgError(e) { //console.log(e) this.isLoadError = true; } }, // 销毁代码 beforeDestroy() { console.log(销毁) this.loaded = false; this.isLoadError = false; } }</script><style lang="scss" scoped> .lazy-image{ height: 100%; width: 100%; flex: 1; display: flex; flex-direction: column; align-items: center; position: relative; image{ width: 100%; } view{ background-color: #eee; position: absolute; z-index: 2; top: 0; left: 0; height: 100%; width: 100%; flex: 1; display: flex; flex-direction: column; align-items: center; transition: opacity 0.4s linear; image{ width: 100%; } } .loaded{ opacity: 0; } }</style>

用 css3动画判读

isLoadError:false 这个熟悉来判断是否加载 然后用透明度来把加载的图片为0 显示对的图片地址
可以吧。。。

面对疾风吧,帮到你了 请点个赞把 啊哈

 

相关文章