小程序使用图片展示的时候,有时候因为各种问题,图片原文件被删除,请求被限制等,会出现图片加载失败,这个可以参见小程序文档,通过binderror来进行处理。
![](https://img.haomeiwen.com/i3120799/de03c2fc816d0668.png)
一、单图处理
<image src="{{picturesUrl}}" binderror="errorImg" lazy-load="true" mode="aspectFill"></image>
1、在js里通过binderror绑定的errorImg进行处理
// 图片加载失败
errorImg(event) {
let noHead = '你的默认图片的地址';
this.setData({
picturesUrl: noHead
})
},
2、如果你的图片是某个对象里的值,可以替换对应的value,如下:
wxml:
<image src="{{user.picturesUrl}}" binderror="errorImg" lazy-load="true" mode="aspectFill"></image>
js:
let img = 'user.picturesUrl', noHead = '你的默认图片的地址';
this.setData({
[img]: noHead
})
同上,如果是替换data里某个对象中的某个值,可以用2的方法操作;
二、多图处理
wxml:
<view class="imgList">
<block wx:for='{{imgList}}'>
<image src="{{item}}" binderror="avatarError" data-index="{{index}}" mode="widthFix" />
</block>
</view>
js:
data: {
imgList:[
'https://upload.jianshu.io/users/upload_avatars/3120799/d78ee51-34c2.png',
'https://upload.jianshu.io/users/upload_avatars/3120799/d778ee51-34c2-41f4-839c-897106dae2ff.jpg',
'https://upload.jianshu.io/users/upload_avatars/3120799/d78ee51-34c2.png'
],
noHead: '/img/noHead.png',
},
//图片加载出错,替换为默认图片
avatarError (e) {
let index = e.currentTarget.dataset.index;
let errorImg = 'imgList[' + index + ']'
this.setData({
[errorImg]: this.data.noHead
})
}
完整代码点此
网友评论