在项目中如果自定义指令太多,不方便在main.js中写。那么如何能够全部写在一个文件然后在main.js中引入。
首先创建一个js文件,用于专门书写指令 directives/index.js
export const imagerror = {
inserted(dom, options) {
console.log(dom)
dom.onerror = function() {
dom.src = options.value
}
}
}
...
在全局main.js中引入directive文件
import * as directives from '@/directives/index'
//用于引入所有directive *
for (var key in directives) {
//遍历指令 key为指令el directive[key]为操作
Vue.directive(key, directives[key])
}
应用
v-imagerror
例子:解决图片失效的问题
index.vue
import defaultImag from '@/assets/common/head.jpg'
data() {
return {
defaultImag
}
},
v-imagerror="defaultImag"
:src="staffPhoto"