点击上方“青年码农”关注
回复“源码”可获取各种资料
使用 Vue 框架开发项目中,遇到个问题,就是在用户提交数据时,如果连续多次点击按钮,会触发多次,导致数据异常,因此需要限制用户短时间内多次点击同一按钮,只触发一次。
1. 自定义指令
利用元素的 disabled 属性,新建自定义指令,preventClick.js
1export default {
2 install(Vue) {
3 Vue.directive('preventClick', {
4 inserted(button, bind) {
5 button.addEventListener('click', () => {
6 if (!button.disabled) {
7 button.disabled = true;
8 setTimeout(() => {
9 but.disabled = false
10 }, 2000)
11 }
12 })
13 }
14 })
15 }
16}
在 main.js 中引入