理论基础
防抖是
闭包的实际应用
-
当持续触发事件 一定时间内没有再触发事件 事件处理函数才会执行一次
-
如果设定的时间到来之前 又一次触发了事件 就重新开始延时
-
触发事件 一段时间内 没有触发 事件执行 肯定是定时器
-
在设定的时间内 又一次触发了事件 重新开始延时 代表的就是重新开始定时器)
-
那么意味着上一次还没有结束的定时器要清除掉 重新开始)
-
let timer
clearInterval(timer)
timer = setTimeout(function(){
},delay)
防抖函数
function debounce(callback, delay) {
let timer
return function (arg) {
clearTimeout(timer)
timer = setTimeout(function () {
callback(arg)
}, delay)
}
}
function func(value) {
console.log(value)
}
var input = document.getElementById('input')
var debounceFn = debounce(func, 1000)
input.addEventListener('keyup', function (e) {
debounceFn(e.target.value)
})
应用--搜索关键字应用
方法一:手写防抖函数
data() {
return {
timer: null
}
},
methods: {
// 获取 联想词数据列表
async loadSearchSuggestion(q) {
...省略其他代码
},
// 防抖函数
myDebounce(val) {
const _this = this
clearTimeout(this.timer)
this.timer = setTimeout(() => {
_this.loadSearchSuggestion(val)
}, 1000)
}
},
watch: {
searchText: {
// 监视的处理函数
handler: function(val) {
this.myDebounce(val)
},
// 首次监视触发
immediate: true
}
}
方法二:使用lodash插件
- 安装 lodash
# yarn add lodash
npm i lodash
- 引入 模块
// lodash 支持按需加载,有利于打包结果优化
import { debounce } from "lodash"
不建议这样使用,因为这样会加载整个模块。
import _ from 'lodash' _.debounce()
- 防抖处理
watch:{
// 监视的输入框输入的文字
searchText:{
// debounce 函数
// 参数1:函数
// 参数2:防抖时间
// 返回值:防抖之后的函数,和参数1功能是一样的
handler: debounce(function (val) {
// 调用【获取联想建议】接口,获取联想词
this.loadSearchSuggestion(val)
}, 1000),
// 首次监视触发
immediate: true
}
}