前端开发中
防重复提交
是一个很头疼又绕不开的话题。
现在我们定义一个指令v-preventReClick
让它专门来干这件事。
talk is cheap, show me the code.
v-preventReClick
src/directive/preventReClick.js
/**
* 防止重复提交指令
* 参考文档 https://juejin.im/post/5eb7fc626fb9a0436a7c6af1#heading-0
*
* @author: tanpeng
* @date : 2020/5/20 18:08
* @version: v1.0.0
*/
const preventReClick = {
install: (Vue, options) => {
Vue.directive('preventReClick', {
inserted: (el, binding) => {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
// 传入绑定值就使用,默认3000毫秒内不可重复点击
setTimeout(() => el.disabled = false, binding.value || 3000)
}
})
}
})
}
}
export default preventReClick
usage
src/main.js
import preventReClick from '@/directive/preventReClick'
// 显示声明为全局指令,代码可读性更好
Vue.use(preventReClick)
src/Demo.vue
// 指定延迟时间1000ms
<a-button size="large" type="primary" v-preventReClick="1000">保 存</a-button>
// 默认延迟时间3000ms
<a-button size="large" type="primary" v-preventReClick>保 存</a-button>