第一步:创建defaultImg.js
const img = require('../assets/img/positionImg.png')
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;//如果想要指定图片用到这个地方,下面的img也要同时改动
if (imgURL) {
const exist = await imageIsExist(imgURL);
if (exist) {
el.setAttribute('src', imgURL);
} else {
el.setAttribute('src', img);
}
} else {
el.setAttribute('src', img);
}
})
}
export default { install };
第二步:main.js引入
import defaultImg from './utils/defaultImg';
Vue.use(defaultImg);
第三步:使用
<!--这里使用指令v-default-img,如果想要指定默认展示的图片需要v-default-img="defaultImgUtl",然后改动js,具体看js中注释的说明-->
<img :src="text" alt="" v-default-img />
网友评论