使用示例
<swiper :indicator-dots="true" :indicator-color="dotColor" :indicator-active-color="actdotColor">
<swiper-item v-for="(item, i) in list" :key="item.id" @click="itemClick">
<view class="swiper-item">
<image
:src="item.url" mode=""
@error="$imgerr($event,list,i,'url')"></image>
</view>
</swiper-item>
</swiper>
export default{
data(){
return{
actdotColor:'#fdfdfd',
dotColor:'#222337',
list:[
id: i,
url: 'xxxx'
]
}
}
}
<image :src="info.avatarUrl"
@error="$objImgerr($event, info, 'avatarUrl')"></image>
export default{
data(){
return{
info:{
nickName:"ggg,
avatarUrl:'http://xxxx.png'
},
}
}
}
配置main.js
Vue.prototype.$imgerr = imgErr
Vue.prototype.$objImgerr = imgObjErr
工具方法
tool.js
export const DEFAULT_IMG = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2668008602,2547122991&fm=26&gp=0.jpg" //默认图片
export const ERROR_IMG = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=314921266,1509694118&fm=26&gp=0.jpg" //错误图片
/
**图片错误处理
* @param {Array} e 错误返回的对象
* @param {Array} arr 数据源 [{url:'xxx'}]
* @param {number|string} i 索引
* @param {Array:string} field 字段名
* @param {string} url 指定错误图片路径
*/
export function imgErr(e, arr, i, field, url){
if(getErrUrl(e.detail.errMsg) !== ERROR_IMG){
if(typeof field === 'string'){
return arr[i][field] = url || ERROR_IMG
}else{ // array
field.reduce((prev, curr, i)=>{
if(i === field.length - 1){
prev[curr] = ERROR_IMG
}
return prev[curr]
},arr[i])
}
}
throw new Error('错误图片路径错误!!!')
}
// vue实例属性
export function imgObjErr(e, obj, attr, url){
if(getErrUrl(e.detail.errMsg) !== ERROR_IMG){
return obj[attr] = url || ERROR_IMG
}
throw new Error('错误图片路径错误!!!')
}
function getErrUrl(url){
let str = ''
if(url.startsWith('GET ')){
str = url.substr(4)
}
if(url.endsWith('404 (Not Found)')){
str = str.substr(0, str.length - 16)
}
return str
}