nuxt服务端渲染 vue检测图片加载失败onerror时,自定义指令处理
全局注册自定义指令,用于判断当前图片是否能够加载成功,可以加载成功则赋值为img的src属性,否则使用默认图片。
在网络慢的时候,加载图片多的时候,可以达到占位图的效果
// plugins/directive.jsimport Vuefrom"vue";/**
* 全局注册自定义指令,用于判断当前图片是否能够加载成功,可以加载成功则赋值为img的src属性,否则使用默认图片
* 在网络慢的时候,加载图片多的时候,可以达到占位图的效果
* 使用方法:<img src="默认图片.png" v-real-img="真实图片.png">
*/
Vue.directive('real-img',asyncfunction(el, binding){//指令名称为:real-imglet imgURL= binding.value;//获取图片地址if(imgURL){let exist=awaitimageIsExist(imgURL);if(exist){
el.setAttribute('src', imgURL);}}})/**
* 检测图片是否存在
* @param url
*/letimageIsExist=function(url){returnnewPromise((resolve)=>{var img=newImage();
img.onload=function(){if(this.complete==true){resolve(true);
img=null;}}
img.onerror=function(){resolve(false);
img=null;}
img.src= url;})}// 在nuxt.config.js 中配置{ src:"~/plugins/directive.js", ssr:false}// index.vue中使用<img src="图片占位地址.png"
v-real-img="图片真实地址.png"
alt="">