vue 全局指令实现防止按钮重复点击 防抖
指令代码
export const preventClick = {
inserted(el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 3000)
}
})
}
}
附:批量定义全局指令
定义指令
1、创建components/directive/directive.js
export const clickoutside = {
bind: function(el) {
const dom = el.querySelector('.el-input__inner')
if (dom) {
dom.addEventListener('focus', function() {
setTimeout(() => {
dom.removeAttribute('readonly')
}, 200)
})
}
}
}
export const preventClick = {
inserted(el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 3000)
}
})
}
}
export default { clickoutside, preventClick }
2、创建components/directive/index.js
import directives from './directive'
const directiveInstalls = []
const directiveList = []
Object.keys(directives).forEach(key => {
const install = function(Vue) {
Vue.directive(key, directives[key])
}
directives[key].install = install
directiveInstalls.push(install)
directiveList.push(directives[key])
})
if (window.Vue) {
Object.keys(directives).forEach(key => {
window[key] = directives[key]
})
directiveInstalls.forEach(install => {
Vue.use(install);
})
}
export default directiveList
3、在main.js引入全局指令,或在指定vue文件作为局部指令引入
import directives from '@/components/directive'
directives.forEach(directive => {
Vue.use(directive)
})