Prevent users from frequently clicking buttons in vue

Method 1: Define a variable (such as: flag) to control the disabled attribute of the button, thereby preventing the user from clicking the button multiple times in a short period of time. Method 2: Define
a command globally, and control the interval between button clicks by binding the command to the button
Method 3: You can only click once.

Specific implementation:
Method 1 steps:
① First set the variable flag attribute value to false, so that the button can be clicked (disabled: true)
② When the user clicks, immediately set the button to be unclickable (disabled: false)
③ Wait for the event to be executed or the corresponding After an interval, restore the button to the clickable state

<el-button @click="clickBtn" :disabled="flag">按钮</el-button>
export default{
    
    
	data(){
    
    
		return {
    
    
			flag: false, // 控制按钮的disabled属性
		}
	},
	methods: {
    
    
		clickBtn(){
    
    
		 	// 设置按钮不可点击(disable: false)
			this.flag = true
			// 执行耗时间的代码或事件请求等....
			
			// 等待事件执行完或者相应的间隔时间后,恢复按钮为可点击状态
			setTimeout(() => {
    
    
				this.flag = false
			}, 1000)
		}
	}
}

Method 2:
① First create a directive file (such as: directive.js file)
② Create a global directive in the directive.js file (such as: preventReClick)
③ Set the binding according to the disabled state value of the button element in the directive Determine the state of the button (for example, change the background color and border color of the button)
④ Then introduce instructions in the entry file main.js file
⑤ Bind and specify on the button that needs to prohibit repeated clicks

====== directive.js文件中 ====
import Vue from 'vue'
const preventReClick = Vue.directive('preventReClick',{
    
    
	inserted: function(el, binding, vNode, oldVnode){
    
    
		el.addEventListener('click', () => {
    
    
			if(!el.disabled){
    
    
			    el.disabled = true
			    el.style.backgroundColor = '#ccc'
			    el.style.border = 'none'
       			setTimeout(() => {
    
    
          			el.disabled = false
          			 el.style.backgroundColor = '#1890ff'	
          			 el.style.border = '1px solid #1890ff'
        		}, 2000)
			}
		})
	}
})

export default {
    
    
	preventReClick 
}


====== 在main.js文件中引入指令 =====
import {
    
    preventReClick } from './directive/directive.js'
Vue.use(preventReClick )

Then add v-preventReClick to the el-button to achieve the effect. After clicking, the button becomes disabled for two seconds, and can be submitted again after two seconds.

	// 添加新属性
<el-button type="primary" @click="handleSave" v-preventReClick>保存</el-button>

Guess you like

Origin blog.csdn.net/qq_52099965/article/details/127581099