美文网首页
Vue 图片加载失败显示默认图片的方法

Vue 图片加载失败显示默认图片的方法

作者: 深渊凝视 | 来源:发表于2022-08-29 10:48 被阅读0次

项目中经常会遇到图片加载失败需要显示默认图片的场景,那么如何在图片src资源加载失败显示出默认的图片呢?

方法一:onerror

<img src="加载图片Url" onerror="默认图片路径"/>

在vue项目中需加bind:

<img :src="imgUrl" :onerror="defaultImgUrl"/>
export default {
  data(){
      return {
          imgUrl:  require('加载图片路径'),
          defaultImgUrl: require('默认图片路径')
      }
  }  
}

方法二:

自定义指令 defaultImg.js:

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;
    if (imgURL) {
      const exist = await imageIsExist(imgURL);
      if (exist) {
        el.setAttribute('src', imgURL);
      } else {
        el.setAttribute('src', defaultURL);
      }
    } else {
      el.setAttribute('src', defaultURL);
    }
  })
}
export default { install };

main.js使用自定义指令

import defaultImg from './directives/defaultImg';
Vue.use(defaultImg);

在vue项目中使用:

<img :src="imgUrl" v-default-img="defaultImgUtl"/>

相关文章

网友评论

      本文标题:Vue 图片加载失败显示默认图片的方法

      本文链接:https://www.haomeiwen.com/subject/zkvhnrtx.html