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 @   东八区  阅读(575)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示