Usually, the pictures we set can be displayed normally, but sometimes the picture loading fails due to the invalidation of the picture path, so we have to set the backup picture to be displayed by default for the picture, which can be solved by using a custom command.
Register custom command method
Vue.directive('指令名称', {
// 会在当前指令作用的dom元素 插入之后执行
// options 里面是指令的表达式
inserted: function (dom,options) {
}
})
We may register multiple custom instructions in the project, so it is impossible for us to register the instructions one by one. Here, we can use a modular method to unify registration and management
src/directives/index.js
Manage custom directives in
export const imagerror = {
// 指令对象 会在当前的dom元素插入到节点之后执行
inserted(dom, options) {
// options是 指令中的变量的解释 其中有一个属性叫做 value
// dom 表示当前指令作用的dom对象
// dom认为此时就是图片
// 当图片有地址 但是地址没有加载成功的时候 会报错 会触发图片的一个事件 => onerror
dom.onerror = function() {
// 当图片出现异常的时候 会将指令配置的默认图片设置为该图片的内容
// dom可以注册error事件
dom.src = options.value // 这里不能写死
}
}
}
main.js
Register a global custom directive
// import * as 变量 得到的是一个对象 { 变量1:对象1,变量2: 对象2 ... }
import * as directives from '@/directives'
// 注册自定义指令
// Object.keys将对象属性转化为数组形式然后进行遍历
// 遍历所有的导出的指令对象 完成自定义全局注册
Object.keys(directives).forEach(key => {
// 注册自定义指令
Vue.directive(key, directives[key])
})
组件中使用自定义指令
<img v-imageerror="defaultImg" :src="Photo">
data() {
return {
defaultImg: require('@/assets/common/default.jpg')
}
},
The hook function of the custom instruction can be seen on the official website
of the custom instruction address