首先在根目录下建立directives文件夹,在里面建立index.js(名字不固定要求注意避开保留字)
里面只做导入指令,全局导出
比如注册一个防抖
import { debounce, A,B} from './instruction';//指令加多少就写在这个文件里,在花括号和下面的申明下
// 自定义指令
const directives = {
debounce, A, B
};
// 批量注册指令
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
}
然后再建立一个写指令的js文件--这里以instruction.js做列
const debounce = {
inserted: function(el, binding) {
let timer;
el.addEventListener("click", () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
binding.value();
}, 1000);
});
}
}
const A = {
//指令A的函数
}
const B = {
//指令A的函数
}
export { debounce, A ,B }
在main.js 全局 (注意路径名字!)
import Directive from './directives/index.js'
Vue.use(Directive)
使用:
<el-button v-debounce="debounceClick">确定</el-button>
methods: {
debounceClick () {
console.log('你好!')
//将要执行的函数放这里调用
this.logTxt()
},
logTxt () {
console.log('是的我好')
},
}