遇到过好多次了,但是还是记不住,人老了,干脆写出来,以后就回来翻出来看
日常开发需求:防止按钮短时间多次点击
啥叫防抖和节流
防抖是将多次执行任务变成最后一次来执行,节流是将多次执行变成间隔一段时间再去执行
防抖:任务频繁触发的时候,只有任务触发实践间隔超过指定间隔的时候,任务才会执行
data () {
timer: null //创建一个标记用来存放定时器的返回值
}
//封装定时器清除函数
clearTimer () {
if (this.timer) clearTimer(this.timer)
}
//点击的事件
goToNext () {
this.clearTimer() //先执行定时器清除函数,如果以前设定过了,就把它前一个定时器清除掉
//然后重新创建一个新的setTimeout
this.timer = setTimeout( () => {
//随意写的一些逻辑
this.qaIndex = this.qaIndex + 1
this.currentBtn = ''
this.progress()
},500)
}
结合上面的代码,我们可以了解到,在触发点击事件后,如果用户再次点击了,我们会清空之前的定时器,重新生成一个定时器。意思就是:这件事儿需要等待,如果你反复催促,我就重新计时!
节流:用户点击提交按钮,假设我们知道大致的返回时间,我们使用节流,这里只允许用户进行一次点击
data(){
ageNum: '',
phoneNum: '',
btnDisable: false
}
submitFace(){
if(!this.ageNum){
wepy.showToast({
title: '请填写您的年龄',
icon: 'none',
duration: 2000
})
}
if(!this.phoneNum){
wepy.showToast({
title: '请填写微信/手机号',
icon: 'none',
duration: 2000
})
}
if(this.ageNum && this.phoneNum){
// 2. 在函数开头判断标志是否为 true,为true 则中断函数
if(this.btnDisable) return
wepy.showLoading({
title: '提交中...',
mask: true
})
this.btnDisable = true // 1. 防止多次提交不断发请求
this.$emit('btnDisable',this.btnDisable)
wepy.request({
url: '/mobile/mina/face/save',
method: 'POST',
data: {
age: this.ageNum,
phone: this.phoneNum,
problemTypeList: this.saveTagList
}
}).then((res) => {
wepy.hideLoading()
if (res.resCode != 0) return
wepy.showToast({
title: '信息提交成功',
icon: 'success',
duration: 2000
})
this.btnDisable = false // 3. 交成功后重置为false 变为可点状态
}
}
}