默认头像

195 阅读1分钟
/directives/index.js
export const imageerror = {
  inserted(dom, options) { // 创建时触发,这时候dom加载完成
    dom.src = dom.src || options.value
    dom.onerror = () => {
      dom.src = options.value// options.value传进来的默认蹄片地址
    }
  },
  componentUpdated(dom, options) { // 指令所在组件的VNode及其子VNode全部更新后调用
    dom.src = dom.src || options.value
  }
}

1. 在需要使用的组件中引入该代码:

import { imageerror } from '@/directives/imageerror.js'

2. 在该组件的template中的img标签上使用v-imageerror指令:

<img v-imageerror="defaultImg" :src="imgUrl">
data() {

    return {
      defaultImg: require('@/assets/common/head.jpg')
    }
  },
其中,'defaultImg'为默认图片地址,:src="imgUrl"为需要加载的图片地址。

3. 在该组件的directives属性中注册该指令:

directives: {
  imageerror
}

这样,当需要加载的图片地址出错时,就会自动替换为默认图片地址。