前言
用uniapp 開發小程序,商品的列表頁面,當然需要用到懶加載了,
當然我寫的這個拉加載 只是針對效果圖,但是也很炫酷,適合列表哦!!
啊哈
原理其實就是用了
@load 和error 的2個方法來判斷是否加載完全 和出錯
<image class="real-image" @load="onLoaded" :src="realSrc" :mode="mode" @error="handleImgError"> </image>
然后就是代碼周小程序期邏輯了:
我封裝了成了了組件,還是看代碼吧,啊哈
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 顯示對的圖片地址
可以吧。。。
面對疾風吧,幫到你了 請點個贊把 啊哈