import Vue from 'vue' import onlyNumber from './onlyNumber' /** * 全局注册自定义指令,用于判断当前图片能否加载成功,可以加载成功赋值img的src属性,否则使用默认图片 * 在网络慢的时候,加载图片多的时候,可以达到占位效果 * 使用方法: */ Vue.directive('real-img', async function (el, binding) { let imgUrl = binding.value; // 获取图片地址 if (imgUrl) { let exist = await imgIsExist(imgUrl) if (exist) { el.setAttribute('src', imgUrl) } } }) /** * 检测图片是否存在 */ let imgIsExist = 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('onlyNumber', onlyNumber)