// 节流
export const debounce = (that, fun, wait) => {
if (that.timer) {
clearTimeout(that.timer);
}
that.timer = setTimeout(() => {
fun();
}, wait);
}
具体使用 -- VUE2环境下
<script>
//注意,这里模拟的是VUE文件的环境状态下,按步骤直接套用即可
//外部JS文件 public.js
// export const debounce = (that, fun, wait) => {
// if (that.timer) { clearTimeout(that.timer); }
// that.timer = setTimeout(() => {
// fun();
// }, wait);
// }
//由于此处用的是箭头函数,所以内部不能用this,通过外部传入解决,参数为that
//fun,为传入函数
//wait,为时间
</script>
<!-- Test.vue -->
<template>
<!-- 此处模拟vue的渲染区,@click调用防抖后函数 -->
<div class="operate">
<el-button type="success" @click="textFunDebounce">Enter 确定</el-button>
</div>
</template>
<script>
import { debounce } from "@/src/util/public";
export default {
methods: {
//调用防抖
textFunDebounce() {
//第一个this,为参数that的实际传参,解决指向问题
//this.textFun为传入函数,由于此函数需要传参,所以后面使用 .bind(this,参数) 进行 —— 此项请各自查资料
//300,为防抖时间
debounce(this,this.textFun.bind(this,"我是传参page"),300)
},
//需要防抖的函数
textFun(page) {
console.log("延迟成功", page);
}
}
}
</script>