vue 优雅的实现防抖和节流

防抖和节流的应用场景

防抖(debounce): n 秒后执行该事件,若在n秒后被重复触发,则重新计时

节流(throttle): n 秒内只运行一次,若在n秒内重复触发,只有一次生效

 

安装 lodash

yarn add lodash
npm i lodash -s |  npm install --save   

 

导入lodash

import _ form "lodash"
_: 根据需求进行自定义

 

vue2 中优雅的使用防抖和节流

案例:
<template>
  <button @click="btn1"></button>
</template>
​
<script>
  methods: {
  btn1 () {
    this.btn2();
    this.btn3();
  },
  btn2:_.debounce(function(){
    console.log('防抖')
  },1000),
  btn2:_.throttle(function(){
    console.log('节流')
  },1000)
}
</script>

 

vue3 中优雅的使用防抖和节流

<template>
  <button @click="btn1"></button>
   <button @click="btn2"></button>
</template>
​
<script>
  setup() {
    //防抖
    const btn1 = _.debounce(function() {
      console.log('防抖');
    }, 2000);
    //节流
    const btn2 = _.throttle(function() {
      console.log('节流');
    }, 2000);
    return {
      btn1,
      btn2,
    };
</script>
posted @ 2022-07-01 17:11  东八区  阅读(532)  评论(0编辑  收藏  举报