如何防止按钮短时间内连续点击多次调用函数?
要确保在短时间内连续点击按钮只会调用一次UploadData()函数,可以通过设置一个标志位来实现。
首先,在组件中定义一个变量,例如isUploading,用于标识是否正在上传数据。初始化时,将该变量设置为false。
然后,在UploadData()函数中,添加判断逻辑,只有当isUploading为false时才执行上传操作,并将isUploading设置为true。上传完成后,将isUploading重新设置为false。
最后,在点击按钮的地方,添加一个事件处理函数,该函数会先判断isUploading是否为false,如果为false则调用UploadData()函数。
以下是修改后的代码示例:
// 初始化变量
data() {
return {
isUploading: false,
// 其他数据
// ...
}
},
// 上传数据函数
methods: {
UploadData() {
if (!this.isUploading) {
// 设置标志位
this.isUploading = true;
// 发起上传请求
axios.post(url, {
a: {
a: this.a,
b: this.b,
},
}).then(res => {
// 上传完成后重置标志位
this.isUploading = false;
});
}
},
},
// 点击按钮触发的事件处理函数
handleButtonClick() {
if (!this.isUploading) {
this.UploadData();
}
},
这样,当在短时间内连续点击按钮时,只有第一次点击会触发上传操作,后续点击会被忽略,直到上传完成后才能再次触发上传操作。
原文地址: https://www.cveoy.top/t/topic/qhJL 著作权归作者所有。请勿转载和采集!