项目中经常会遇到图片加载失败需要显示默认图片的场景,那么如何在图片src资源加载失败显示出默认的图片呢?
方法一:onerror
<img src="加载图片Url" onerror="默认图片路径"/>
在vue项目中需加
bind
:
<img :src="imgUrl" :onerror="defaultImgUrl"/>
export default {
data(){
return {
imgUrl: require('加载图片路径'),
defaultImgUrl: require('默认图片路径')
}
}
}
方法二:
自定义指令 defaultImg.js
:
function install(Vue, options = {}) {
/**
* 检测图片是否存在
* @param url
*/
let imageIsExist = function (url) {
return new Promise((resolve) => {
var img = new Image();
img.onload = function () {
if (this.complete == true) {
resolve(true);
img = null;
}
}
img.onerror = function () {
resolve(false);
img = null;
}
img.src = url;
})
}
Vue.directive(options.name || 'default-img', async function (el, binding) {//指令名称为:v-default-img
const imgURL = el.src;//获取图片地址
const defaultURL = binding.value;
if (imgURL) {
const exist = await imageIsExist(imgURL);
if (exist) {
el.setAttribute('src', imgURL);
} else {
el.setAttribute('src', defaultURL);
}
} else {
el.setAttribute('src', defaultURL);
}
})
}
export default { install };
在
main.js
使用自定义指令
import defaultImg from './directives/defaultImg';
Vue.use(defaultImg);
在vue项目中使用:
<img :src="imgUrl" v-default-img="defaultImgUtl"/>
网友评论