zoukankan      html  css  js  c++  java
  • 函数节流、函数防抖的原理以及lodash的节流(throttle) 和 防抖(debounce)在vue+ts中的使用

    安装依赖

    npm i throttle-debounce-ts

    区别:

    1. 函数节流在特定时间内触发一次任务,并且是规律的
    2. 函数防抖只有最后一次延时时间到达之后执行一次

    应用场景:

    • throttle
    1. 鼠标不断点击触发,mousedown(单位时间内只触发一次)
    2. 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断
    • debounce
    1. 百度搜索,用户在不断输入值时,用防抖来节约请求资源。
    2. window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

    lodash 的 节流(throttle) 和 防抖(debounce)
    例:每隔300毫秒执行一次 onConfigDialogClick函数

    <el-button type="primary" @click="saveDebounce">确 定</el-button>
    
    //引用
    import { throttle} from 'throttle-debounce-ts';
    
    //使用
    private saveDebounce = throttle(300, this.onConfigDialogClick);
    
    // 点击确定按钮
      onConfigDialogClick() {
        const verifyResult = this.templateEditer.formVerifyResult();
        if (verifyResult !== '') {
          this.$message.warning(verifyResult);
          return;
        }
       //请求数据
        this.onRequestDataChanged();
      }

    例:在停止点击300毫秒后,调用onConfigDialogClick方法

    <el-button type="primary" @click="saveDebounce">确 定</el-button>
    
    //引用
    import { debounce } from 'throttle-debounce-ts';
    
    //使用
    private saveDebounce = debounce(300, this.onConfigDialogClick);
    
    // 点击确定按钮
      onConfigDialogClick() {
        const verifyResult = this.templateEditer.formVerifyResult();
        if (verifyResult !== '') {
          this.$message.warning(verifyResult);
          return;
        }
       //请求数据
        this.onRequestDataChanged();
      }
  • 相关阅读:
    vue中$router和$route的区别
    移动端rem自适应
    如何用Mac自带的QuickTime Player录制视频并制作GIF动图
    vue页面刷新重定向
    JavaScript Functional Programming:声明式与命令式
    配置一个可以使用Vue的History模式的后端服务
    vue使用jsx语法开发
    vue多页面项目配置
    JavaScript的本来面貌之默认结构
    JavaScript的本来面貌之默认值
  • 原文地址:https://www.cnblogs.com/xiaoxiaomini/p/14217482.html
Copyright © 2011-2022 走看看