防抖: 用户在短时间内多次触发事件时,只取最后一次触发结果
节流: 用户在短时间内多次触发事件时,将次数压缩一次,取决于定时器设定的时间
创建common.js文件
// 防抖
let timeout = null
export const testFun = (fun, time = 500) => {
if(timeout){
clearTimeout(timeout) // 规定时间内若定时器存在则清除
}
timeout = setTimeout(() => {
console.log('触发点击')
fun() // 调用接口
}, time);
}
// 节流
let flag = true
export const testFun2 = (fun, time = 500) => {
if(flag) {
setTimeout(() => {
console.log('触发点击')
fun() // 调用接口
flag = true // 在定时器执行后 移除if阻断
}, time);
}
flag = false // 在执行一次后 if阻断定时器继续执行
}
vue页面使用:
import { testFun } from "../common";
export default {
methods: {
testClick() {
testFun(this.pushApi) // 这里不能调用方法,只是将方法传过去,防抖方法中触发
},
pushApi() {
console.log("请求接口触发")
}
}
}
import { testFun } from "../common";
export default {
data() {
return {
value: "" // 文本框值
}
}.
watch: {
value() {
testFun2(() => {
this.pushApi()
}, 1000)
}
},
methods: {
pushApi() {
console.log("请求接口触发")
}
}
}