一、自己封装方法实现:
1、何谓节流和防抖?
节流
节流的意思是,规定时间内,只触发一次。比如我们设定500ms,在这个时间内,无论点击按钮多少次,它都只会触发一次。具体场景可以是抢购时候,由于有无数人 快速点击按钮,如果每次点击都发送请求,就会给服务器造成巨大的压力,但是我们进行节流后,就会大大减少请求的次数。防抖
防抖的意思是,在连续的操作中,无论进行了多长时间,只有某一次的操作后在指定的时间内没有再操作,这一次才被判定有效。具体场景可以搜索框输入关键字过程中实时 请求服务器匹配搜索结果,如果不进行处理,那么就是输入框内容一直变化,导致一直发送请求。如果进行防抖处理,结果就是当我们输入内容完成后,一定时间(比如500ms)没有再 输入内容,这时再触发请求。
2、具体实现:
节流:
throttle(func,wait = 500)
func
<Function> 触发回调执行的函数wait
<Number> 时间间隔,单位ms
let timer_throttle = null
const throttle = (func, wait) => {
if (!timer_throttle) {
timer_throttle = setTimeout(() => {
func.apply(this, arguments)
timer_throttle = null;
}, wait)
}
}
防抖:
debounce(func,wait = 500)
func
<Function> 触发回调执行的函数wait
<Number> 时间间隔,单位ms
let timer_debounce = null
const debounce = function(func, wait) {
if (timer_debounce) {
clearTimeout(timer_debounce)
timer_debounce = null;
}
timer_debounce = setTimeout(() => {
func.apply(this, arguments)
}, wait)
}
3、使用:
可以在uilts文件夹下新建prototype.js文件:
//防抖
let timer_debounce = null
const debounce = function(func, wait) {
if (timer_debounce) {
clearTimeout(timer_debounce)
timer_debounce = null;
}
timer_debounce = setTimeout(() => {
func.apply(this, arguments)
}, wait)
}
//节流
let timer_throttle = null
const throttle = function(func, wait) {
if (!timer_throttle) {
timer_throttle = setTimeout(() => {
func.apply(this, arguments)
timer_throttle = null;
}, wait)
}
}
export default {
throttle,
debounce
}
在main.js全局引入挂载:
import prototype from './uilts/prototype.js'
Vue.prototype.$prototype = prototype
在vue页面中使用:
let that = this
this.$prototype.debounce(function() {
console.log('防抖', that.inputValue)
}, 500)
let that = this
this.$prototype.throttle(function() {
console.log('节流', that.inputValue)
}, 500)
二、使用 Lodash 等组件库来实现:
安装组件库:
npm i --save lodash
或
yarn add lodash
引入挂载组件库:
import _ from "lodash";
节流、防抖函数:
_.throttle(func, [wait=0], [options=])//节流
//说明:
//func (Function): 要节流的函数。
//[wait=0] (number): 需要节流的毫秒。
//[options=] (Object): 选项对象。
//[options.leading=true] (boolean): 指定调用在节流开始前。
//[options.trailing=true] (boolean): 指定调用在节流结束后。
_.debounce(func, [wait=0], [options=])//防抖
//说明:
//func (Function): 要防抖动的函数。
//[wait=0] (number): 需要延迟的毫秒数。
//[options=] (Object): 选项对象。
//[options.leading=false] (boolean): 指定在延迟开始前调用。
//[options.maxWait] (number): 设置 func 允许被延迟的最大值。
//[options.trailing=true] (boolean): 指定在延迟结束后调用。
使用节流、防抖函数:
_.debounce(() => {
console.log("防抖");
}, 500);
_.throttle(() => {
console.log("节流");
}, 500);