防抖:
概念:某一段时间内多次事件合并为一次执行,注意事件可多次触发但只执行一次
<input v-model="searchKey" placeholder="请输入关键字搜索文章"/>
// 在输入时一直触发watch事件就很烦,所以使用防抖可避免多次
watch: {
searchKey (val) {
if (!val) {
if (this.timer) {
clearInterval(this.timer)
}
this.articleList = []
this.timer = null
return
}
if (!this.timer) {
this.timer = setTimeout(() => {
this.$api.searchAritcle({title: val}).then(res => {
if (res.success) {
this.showEmpty = res.obj.length === 0
this.articleList = res.obj
}
})
}, 1000)
} else {
clearInterval(this.timer)
this.timer = setTimeout(() => {
this.$api.searchAritcle({title: val}).then(res => {
if (res.success) {
this.showEmpty = res.obj.length === 0
this.articleList = res.obj
}
})
}, 1000)
}
}
}
节流:
概念:一定周期时间内,事件只触发一次。比如滑动触底时要加载新数据,这里触底一次就加载就行。
// 思路一:一个时间段内只触发一次
·······省略触底事件条件··············
// seconds为2秒的时间戳大小,这里博主也不知道
const endTime = new Date().getTime
if (endTime - this.startTime > seconds) {
this.startTime = endTime // 记录触发事件的时间戳初始值为0
console.log('执行触底事件的操作')
}
// 一次触底事件完成之后,才能进行下一次
·······省略触底事件条件··············
if (this.doBottom) {
this.doBottom = false
console.log('执行触底事件的操作')
// 操作执行完之后
this.doBottom = true
} else {
return
}
定时器清理:
清理定时器时,单独的赋值为null是无效的且还是会执行,必须要使用clearInterval()
注意:clearInterval()清除了定时器之后this.timer会变成一个类型为Number的数字,所以!this.timer为false,这样验证码就只能获得一次,下次就不生效了。所以要设置为null
// 这里还没有调用接口获取验证码,就随便写了个
takeCode () {
if (!this.timer) {
this.loginForm.code = '4396'
this.hasCode = true
this.timer = setInterval(() => {
this.seconds-- // 初始为60
if (this.seconds <= 0) {
this.hasCode = false
this.seconds = 60
clearInterval(this.timer)
this.timer = null
}
}, 1000)
}
}