vue项目中使用引入的图片,当图片损坏,自动展示默认图片

51 阅读1分钟

竹林.jpg

import * as directives from "@/directives/index";

Object.keys(directives).forEach((key) => {
  Vue.directive(key, directives[key]);
});


/**
 * 当图片出现损坏时,使用默认图片展示
 */
export const errorimg = {
  // 在当前的dom元素插入到节点之后执行
  inserted(el, options) {
  // 需要以require方式去导入图片
    const defaultStation = require("@/assets/common/error.png");
    el.onerror = function () {
      el.src = defaultStation;
    };
  }
};

//使用
<img v-errorimg> </img>