/directives/index.js
export const imageerror = {
inserted(dom, options) {
dom.src = dom.src || options.value
dom.onerror = () => {
dom.src = options.value
}
},
componentUpdated(dom, options) {
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
}
这样,当需要加载的图片地址出错时,就会自动替换为默认图片地址。