1、在app.json中注册为全局组件
1.1image.wxml
<view class='image-pre-wrapper'>
<image class='{{imageLoaded?"":"image-hide"}}' style='width: {{width}}rpx;height: {{height}}rpx;' mode="{{mode}}" src='{{src}}' bindload='imageLoadHandle' />
<slot name='slot-status' wx:if='{{imageLoaded}}'></slot>
<view class='loading-area' wx:if='{{!imageLoaded}}' style='width: {{width}}rpx;height: {{height}}rpx;'>
<image class='loading' mode='widthFix' src="./loading.gif" />
</view>
</view>
1.2image.js
/**
* 图片预处理组件
*/
Component({
options: {
multipleSlots: true
},
properties: {
width: {
type: String,
value: '750',
},
height: {
type: String,
value: '300',
},
mode: {
type: String,
value: '',
},
src: {
type: String,
value: '',
},
},
data: {
imageLoaded: false, // 图片是否加载完成
},
attached() {},
methods: {
imageLoadHandle(e) {
// 监听image加载完成
setTimeout(()=>{
this.setData({
imageLoaded: true,
})
}, 200);
this.triggerEvent('load', e.detail);
},
}
})
1.3less
.image-pre-wrapper {
position: relative;
overflow-x: hidden;
.image-hide{
position: absolute;
z-index: -99;
opacity: 0;
}
.loading-area {
background: #f2f5f7;
.flex(row, center, center);
.loading {
width: 50rpx!important;
height: 50rpx!important;
// animation: loading_run 1s linear infinite;
}
}
}
2、组件中使用
<comp-image-pre mode='widthFix' width='200' src="./img1.png"></comp-image-pre>