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

序:

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

一、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);

猜你喜欢

转载自blog.csdn.net/MoXinXueWEB/article/details/127782686
今日推荐