一分钟带你搞定前端”防抖节流“

简介: js

序:

项目中必不可少都会用到防抖和节流,于是今天就总结下常规用法。

一、lodash.js防抖节流

1.下载lodash

# Yarn
$ yarn add lodash
$ yarn add lodash-es
# NPM
$ npm install lodash --save
$ npm install lodash-es --save

2.引入lodash

//引入到 main.js 文件中
import lodash from "lodash";
import { debounce } from "lodash-es";

// 将全局lodash对象指向给Vue作用域下
app.config.globalProperties.$lodash = lodash; 

3.防抖用法

debounce API走起

_.debounce(func, [wait=0], [options={}])

func (Function): 要防抖动的函数。

[wait=0] (number): 需要延迟的毫秒数。

[options={}] (Object): 选项对象。

[options.leading=false] (boolean): 指定在延迟开始前调用,默认false。

[options.maxWait] (number): 设置 func 允许被延迟的最大值。

[options.trailing=true] (boolean): 指定在延迟

结束后调用,默认true。

testDebounce: _.debounce(function() {
  console.log("debounce");
}, 2000, {
  leading: true,
  trailing: false
})

testDebounce: debounce(function() {
  console.log("debounce");
}, 2000)

4.节流用法

throttle API走起

_.throttle(func, [wait=0], [options={}]) func (Function): 要节流的函数。

[wait=0] (number): 需要节流的毫秒数。

[options={}] (Object): 选项对象。

[options.leading=true] (boolean): 指定调用在节流开始前,默认true。

[options.trailing=true] (boolean): 指定调用在节流结束后,默认true。

testThrottle: _.throttle(function() {
  console.log("throttle");
}, 5000, {
  leading: true,
  trailing: false
})

5.vue内对这两种防抖截流的使用方法

<!-- throttling 方法使用 --> 
<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
  methods: {
    throttledMethod: _.throttle(() => {
      console.log('I get fired every two seconds!')
    }, 2000)
  }
}
</script>

<!-- debouncing 方法使用 --> 
<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
  methods: {
    throttledMethod: _.debounce(() => {
      console.log('I only get fired once every two seconds, max!')
    }, 2000)
  }
}
</script>

6.react中使用

test = () => {
  console.log('--------------11111---------------');
  this.fun();//方法调用
}

 //debounce使用
fun = _.debounce(function(e){
  console.log('--------------22222---------------');
}, 5000,{
  leading: true,
  trailing: false,
})

//throttle使用
fun = _.throttle(function(e){
  console.log('--------------22222---------------');
}, 5000,{
  leading: true,
  trailing: false,
})

二、手写防抖节流

1.防抖事件

//就是在你的事件前面加上vm.$lodash.debounce((),500),后面接上多久执行一次
    const addSubtaskClick = vm.$lodash.debounce(() => {
      if (inputData.value === '' || inputData.value === null) {
        return messageInfo.error('请输入内容!')
      } else {
        let childTaskList = [
          {
            title: inputData.value,
          },
        ]
        editTasks({ childTaskList: childTaskList })
        inputData.value = ''
        footerInput.value = false
        emit('modificationsClicl', code)

        // addSubtasks()
      }

      if (MyData.childTaskList.length === 0) {
        showSonMy.value = false
      }
      footerInput.value = false
      inputData.value = null
    }, 500)

2.写节流事件

//就是在你的事件前面加上vm.$lodash.debounce((),500)
  const handerClick = vm.$lodash.throttle((item, index) => {\
            activeCheck.value = index;\
            localStorage.setItem('teamMessage', JSON.stringify(item));\
            store.commit('common/teamMessageChange', JSON.stringify(item));\
            router.push('/myTask');\
        }, 500);
目录
相关文章
|
2月前
|
前端开发 JavaScript API
|
10天前
|
缓存 开发框架 前端开发
前端性能优化【前端必备】(含懒加载,手写防抖、节流等)
前端性能优化【前端必备】(含懒加载,手写防抖、节流等)
16 4
|
2月前
|
前端开发 JavaScript UED
【专栏】前端开发中,为解决用户操作引发的性能问题,常使用debounce(防抖)和throttle(节流)技术
【4月更文挑战第29天】前端开发中,为解决用户操作引发的性能问题,常使用debounce(防抖)和throttle(节流)技术。Debounce确保在一段时间内只执行最后一次事件触发的操作,减少不必要的执行,但有滞后性,适合搜索框实时搜索。Throttle则保证一定时间间隔内函数执行一次,保持固定频率,适用于滚动事件处理和窗口大小调整。两者可借助JavaScript或第三方库实现,需根据场景和需求选择并调整。正确使用能提升应用性能和用户体验。
|
2月前
|
前端开发 JavaScript UED
【前端面经】快手二面:节流和防抖知道吗?
【前端面经】快手二面:节流和防抖知道吗?
22 0
|
2月前
|
前端开发 UED
【Web 前端】防抖与节流的区别
【4月更文挑战第22天】【Web 前端】防抖与节流的区别
|
2月前
|
前端开发
【前端学习】—函数防抖(十)
【前端学习】—函数防抖(十)
|
10月前
|
监控 前端开发
前端经典面试题 | 理解 节流 和 防抖(后附手写节流\防抖)
前端经典面试题 | 理解 节流 和 防抖(后附手写节流\防抖)
|
9月前
|
前端开发
前端性能优化之防抖&节流
前端性能优化之防抖&节流
45 0
|
18天前
|
前端开发 JavaScript 数据库
如何实现前后端分离-----前端笔记
如何实现前后端分离-----前端笔记
|
18天前
|
前端开发 安全 NoSQL
技术笔记:Security前端页面配置
技术笔记:Security前端页面配置