效果图
image.png自定义组件wxml
<!--components/load-img/index.wxml-->
<view class="img-content" style="width: {{imgWidth}};height: {{imgHeight}};">
<image bindload="loadHander" binderror="loadError" src="{{imgUrl}}" lazy-load="true" mode="aspectFill" class="img-real"></image>
<image wx:if="{{isShow == false}}" src="{{imgDefault}}" class="img-def" mode="aspectFit"></image>
</view>
自定义wxss
/* components/load-img/index.wxss */
.img-content {
position: relative;
border-radius: 20rpx;
background: pink;
}
.img-real {
width: 100%;
height: 100%;
border-radius: 20rpx;
}
.img-def {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
border-radius: 20rpx;
background: #c7c6c5;
}
自定义组件js
// components/load-img/index.js
Component({
properties: {
imgWidth: {//设置图片宽
value: '200rpx',
type: String,
},
imgHeight: {//设置图片高
value: '200rpx',
type: String,
},
imgUrl: {//设置加载图片
value: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F7l4gIEpqHJo0Qajr4RqIIOE7frTtnL8UmAGKiMY7hMZbP1618564861181.jpeg&thumbnail=660x2147483647&quality=80&type=jpg',
type: String,
},
imgDefault: {//设置默认图片图片
value: '../../image/default.png',
type: String,
}
},
data: {
isShow: false,//控制是否显示默认图片
},
methods: {
loadHander(e) {//图片加载成功监听事件
this.setData({
isShow: true,
})
},
loadError(e) {//图片加载失败监听事件
this.setData({
isShow: false,
})
}
}
})
自定义组件的使用json
{
"usingComponents": {
"load-img": "../../components/load-img/index"
}
}
自定义组件的使用wxml
<load-img imgUrl="{{imgUrl}}" imgWidth="{{imgWidth}}" imgHeight="{{imgHeight}}"></load-img>
<load-img imgUrl="{{imgUrl1}}" imgWidth="{{imgWidth}}" imgHeight="{{imgHeight}}"></load-img>
自定义组件的使用js
Page({
data: {
imgWidth: '23vw', //calc((100% - 220rpx) / 3)
imgHeight: '23vw',
imgUrl: 'https://img2.baidu.com/it/u=3138084486,1386422053&fm=253&fmt=auto?w=500&h=666',
},
})
网友评论