42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
import type { App } from "vue";
|
|
|
|
export default (app: App<Element>): void => {
|
|
app.directive("real-img", {
|
|
async mounted(el, binding, vnode: any) {
|
|
console.log(el);
|
|
if (el.getAttribute("data-load") == null) el.classList.add("img-hide");
|
|
let imgURL = binding.value; //获取图片地址
|
|
|
|
if (imgURL) {
|
|
let exist = await imageIsExist(imgURL);
|
|
if (exist) {
|
|
el.setAttribute("src", imgURL);
|
|
el.setAttribute("data-load", "1");
|
|
}
|
|
}
|
|
el.classList.remove("img-hide");
|
|
},
|
|
});
|
|
};
|
|
|
|
/**
|
|
* 检测图片是否存在
|
|
* @param url
|
|
*/
|
|
let imageIsExist = function (url: string) {
|
|
return new Promise(resolve => {
|
|
var img: HTMLImageElement | null = new Image();
|
|
img.onload = function () {
|
|
if ((this as any).complete == true) {
|
|
resolve(true);
|
|
img = null;
|
|
}
|
|
};
|
|
img.onerror = function () {
|
|
resolve(false);
|
|
img = null;
|
|
};
|
|
img.src = url;
|
|
});
|
|
};
|