vue中实现防抖和节流
<script>
1.在公共方法中(如 public.js 中),加入函数防抖和节流方法
// 防抖
export default {
_debounce(fn, delay) {
var delay = delay || 200;
var timer;
return function () {
var th = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
fn.apply(th, args);
}, delay);
};
},
// 节流
_throttle(fn, interval) {
var last;
var timer;
var interval = interval || 200;
return function () {
var th = this;
var args = arguments;
var now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
fn.apply(th, args);
}, interval);
} else {
last = now;
fn.apply(th, args);
}
}
}
}
2.在需要使用的组件引用
import { public } from "@/utils/public";
3.在 methods 中使用
methods: {
changefield: public._debounce(function(_type, index, item) {
// do something ... }, 200)
}
</script>
防抖函数的使用场景: 频繁触发、输入框搜索
提交按钮不可重复点击,提交按钮灰度
<template>
<div>
<input type='text' v-model='value' @keydown = "hangleChange">
</div>
</template>
<script>
function debounce(func, wait=1000){ //可以放入项目中的公共方法中进行调用(鹅只是省事)
let timeout;
return function(event){
clearTimeout(timeout)
timeout = setTimeout(()=>{
func.call(this, event)
},wait)
}
}
export default{
name:'',
data(){
return{
value:''
}
},
methods:{
hangleChange:debounce(function(e){
console.log(this.value)
})
}
}
</script>
节流函数的使用场景:频繁触发、onrize,onscroll滚动条
<template>
<div class="scroll" ref="previewText" @scroll.passive="fnScroll">
</template>
<script>
export default{
name:'globalHospot',
data(){
return{
count:0,
fnScroll:() =>{}
}
},
methods: {
fnHandleScroll (e) {
console.log('scroll触发了:' + this.count++, new Date())
},
fnThrottle(fn, delay, atleast){ //节流函数
let timer = null;
let previous = null;
return function(){
let now = +new Date()
if(!previous) previous = now;
if(atleast && now - previous > atleast){
fn();
previous = now;
clearTimeout(timer)
}else{
clearTimeout(timer)
timer = setTimeout(()=>{
fn();
previous = null
},delay)
}
}
}
},
created(){
this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //刚创建时执行
},
}
</script>