用Vue自定义指令来处理图片的异常显示

795 阅读1分钟
  • 我们在项目中, 常常会遇到显示图片的场景, 有时会因为图片地址的问题, 导致图片展示裂开的情况, 我们可以通过 自定义指令 来解决这个问题

我们先来熟悉一下, 自定义指令的用法

  • 定义全局指令
Vue.directive('mydir', { 
    // 当被绑定的元素插入到 DOM 中时, 这个函数被调用
    inserted: function (el) {
    
    } 
  }
)
  • 定义局部指令
directives: {
    // 指令的定义 
    mydir: { 
        inserted: function (el) { 
         
        } 
    } 
}
  • 你可以在 template 上这样使用
<div v-mydir> </div>

我们来解决这个问题

  • 开始之前, 你要先了解 error 这个事件, img 标签在图片异常显示的时候, 会自动触发 error 事件
  1. 定义全局指令
const imgerror = {
  // 在当前的dom元素插入到节点之后执行
  inserted (el, options) {
    el.onerror = function() {
      el.src = options.value // 设置 src 属性的默认值为, 指令绑定的值
    }
  }
}
  1. 注册自定义指令
  Vue.directive(key, directives[key])
  1. 使用
<img v-imgerror="defaultImg" :src="photoUrl" />