就是用户在输入框输入时需要向后台请求关键字信息并展示,需要用到防抖函数
首先新建一个js文件
// 防抖函数
export function debounce (fn, delay) {
// 记录上一次的延时器
var timer = null
delay = delay || 300
return function () {
var args = arguments
var that = this
// 清除上一次延时器
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}
在页面中引用
export default {
name: "",
data() {
answer: "",
timeout: null
},
method: {
change() {
if(this.timeout){
clearTimeout(this.timeout)
}
this.timeout = setTimeout(() => {
console.log(this.answer)
}, 500);
}
}
}