以下指令针对vue3.0
- 第一个对错误图片进行处理
- 第二个对按钮防抖进行处理 (注:vue3.0 是mounted,vue2.0是inserted)
export const imageerror = {
// 指令作用在 图片上的 dom是图片对象
mounted(dom, options) {
// inserted执行的之后 此时 并没有对 src赋值
// 图片有地址 但是地址加载图片失败的时候 会执行一个函数 onerror
dom.src = dom.src || options.value
dom.onerror = function () {
// 监听onerror事件
// options.value就是指令传过来的值
dom.src = options.value // 当图片异常的时候 接收指令传过来的值 让这个值作为头像的备选
}
// 只有src有值 并且加载失败才会触发onerror
},
// 此钩子会在给image赋值之后执行
updated(dom, options) {
dom.src = dom.src || options.value
}
};
/** 自定义指令,对按钮进行防抖处理 */
export const preventReClick = {
mounted(el, binding) {
// console.log("binding-7", binding)
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true;
setTimeout(() => {
el.disabled = false;
}, binding.value || 1000);
};
});
},
};
/** 清除input空格自定义指令 */
export const clearSpaces = {
mounted(el, { value, modifiers }, binding) {
// // 获取真实的inputDOM元素
let input = el.children[0];
try {
// 如果不是el输入框 那么直接返回
if (!input) {
return false
};
input.addEventListener('input', () => {
input.value = input.value.replace(/\s+/g, '');
console.log(input.value);
});
} catch (e) {
console.log(e)
}
},
};
import * as directives from '@/directives';
// directives是所有指令的一个集合
Object.keys(directives).forEach(key => {
// key就是指令名称
app.directive(key, directives[key])
});