1、先在 src 下创建文件夹 directives 用于存放自定义指令
src/
└── directives/
└── image-error/
├── index.js
└── README.md
index.js 代码基本配置
export default {
// 指令生命周期钩子函数
bind(el, binding, vnode) {
// 绑定时的初始化逻辑
},
inserted(el, binding, vnode) {
// 元素插入到DOM中的操作逻辑
},
update(el, binding, vnode, oldVnode) {
// 组件更新时的操作逻辑
},
componentUpdated(el, binding, vnode, oldVnode) {
// 组件更新完成后的操作逻辑
},
unbind(el, binding, vnode) {
// 解绑时的清理逻辑
},
};
README.md文件需要写指令使用方式和注意事项
2、配置多指令配置分发文件
在 directives 新建一个 index.js 文件或者在 public 新建文件 vue-directives.js 主要就是引入自定义指令
import imageError from "./imageError";
const directives = {
imageError,
};
// export default directives
export default {
install(Vue) {
Object.entries(directives).forEach(([name, dir]) => {
console.log(name, dir);
Vue.directive(name, dir);
});
},
};
3、最后在main.js引用注册
import Vue from 'vue';
import directives from '@/directives/index.js';
Vue.use(directives);
4、使用就是标签正常使用
<img v-imageError src="" />
这样配置好以后,就可以正常写指令,写完只需要在分发文件配置一下,就可以全局使用,可扩展性提高了。