1 // 如果自定义指令多的话,再重新开启一个文件专门写自定义指令 太乱了
2 全局注册自定义指令,用于判断当前图片是否能够加载成功,可以加载成功则赋值为img的src属性,否则使用默认图片
3 指令名称为:real-img
4 通用错误图片的处理方法,或者也可以懒加载的样子
5 Vue.directive('real-img',async function (el,binding) {
6 let imgURL = binding.value;获取图片地址
7 if (imgURL) {
8 let exist = await imageIsExist(imgURL);
9 (exist) {
10 el.setAttribute('src',imgURL);
11 }
12 }
13 });
14
15 /**
16 * 检测图片是否存在
17 * @param url
18 */
19 let imageIsExist = (url) {
20 return new Promise((resolve) => {
21 var img = new Image();
22 img.onload = () {
23 if (this.complete == true) {
24 console.log('资源加载');
25 resolve(26 img = null;
27 }
28 29 img.onerror = 30 console.log('资源error'31 resolve(false32 img = 33 34 img.src = url;
35 })
36 };
1 <div class="appd_d_ch_logo">
2 img src="../../assets/img/error/app_d.png" v-real-img="appDetail.icon" alt=""3 </div>
5 let imageIsExist = 6 7 8 img.onload = 9 10 console.log('资源加载'11 resolve(12 img = 14 15 img.onerror = 16 console.log('资源error'17 resolve(18 img = 19 20 img.src =21 22 };
23
24
25
26 单独作用于应用模块的管理
传的是错误的图片
28 Vue.directive('err-img',1)">29 let imgURL = binding.value;30 let realURL = el.src;
31 32 let exist = await imageIsExist(realURL);
33 if (!exist) {
34 el.setAttribute('src'36 37 });