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


    序:

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

    一、lodash.js防抖节流

    1.下载lodash

    # Yarn
    $ yarn add lodash
    $ yarn add lodash-es
    # NPM
    $ npm install lodash --save
    $ npm install lodash-es --save
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.引入lodash

    //引入到 main.js 文件中
    import lodash from "lodash";
    import { debounce } from "lodash-es";
    
    // 将全局lodash对象指向给Vue作用域下
    app.config.globalProperties.$lodash = lodash; 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    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
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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

     
    <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>
    
     
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    二、手写防抖节流

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    华测RTK采集的GPX数据如何带属性转出kml、shp进行后续的管理和分析
    使用Python实现强化学习算法
    2D物理引擎 Box2D for javascript Games 第四章 将力作用到刚体上
    Java正则表达式
    STC89C51基础及项目第13天:小车go、软件调速
    《PostgreSQL物化视图:创建、维护与应用》
    Hadoop对集群的一些操作的命令介绍
    mybatis plus代码生成器
    Docker资源分配--Cgroup
    Re-ID
  • 原文地址:https://blog.csdn.net/MoXinXueWEB/article/details/127782686