1***@qq.com
1***@qq.com
  • 发布:2023-02-10 17:09
  • 更新:2023-02-14 21:36
  • 阅读:283

请教: 函数节流(throttle) 的使用格式

分类:HBuilderX

请教: 函数节流 throttle 的使用格式

比如: 我想访问data中定义的变量myUserName,
我用下面的方法来访问, 会报错, 说未定义myUserName
哪位仁兄指点一下, 该如何书写格式?

<script>    

  export default {    
    data() {    
      return {    
        myUserName:'admin'    
      }    
    },    

    methods: {    

      throttled_login: XXXX引用单元.throttle(()=>{    
        console.log(this.myUserName);  //无法访问到    
      }, 5000)    

    }    
  }    
</script>  
2023-02-10 17:09 负责人:无 分享
已邀请:
1***@qq.com

1***@qq.com (作者)

花了4个小时, 终于搞出来了. 以函数参数形式, 把当前界面的变量,传到throttle中.

如下, 与大家分享一下, 如有更好写法, 请指点我一下, 非常感谢!

(以下是完整可直接使用的代码例子)

<template>  
  <view>  

    <input placeholder="(请输入用户名)" v-model='a1' />  
    <input placeholder="(请输入密码)" v-model='a2' />  
    <button type='warn' @tap="login">登录throttle</button>  

  </view>  
</template>  

<script>  
  /**  
   * @desc 函数节流  
   * @param func 函数  
   * @param wait 延迟执行毫秒数  
   * @param type 1 使用表时间戳,在时间段开始的时候触发 2 使用表定时器,在时间段结束的时候触发  
   */  
  export const throttle = (func, wait = 1000, type = 1) => {  
    let previous = 0;  
    let timeout;  
    return function() {  
      let context = this;  
      let args = arguments;  
      if (type === 1) {  
        let now = Date.now();  

        if (now - previous > wait) {  
          func.apply(context, args);  
          previous = now;  
        }  
      } else if (type === 2) {  
        if (!timeout) {  
          timeout = setTimeout(() => {  
            timeout = null;  
            func.apply(context, args)  
          }, wait)  
        }  
      }  
    }  
  }  

  export default {  
    data() {  
      return {  
        a1: 'ADMIN',  
        a2: '123456'  
      }  
    },  

    methods: {  

      //每隔5秒,才生效一次  
      throttled_login: throttle(function(sName, sPwd) {  
        //通过参数形式,访问到界面的变量A1,A2了!  
        console.log('用户名:' + sName + '  密码:' + sPwd);  

      }, 5000),  

      login() {  
        this.throttled_login(this.a1, this.a2);  
      }  
    }  

  }  
</script>  
1***@qq.com

1***@qq.com (作者)

自已顶一下,希望引起大家关注

1***@qq.com

1***@qq.com (作者)

      throttled_login88: kStrUtils.throttle(function(){      
        console.log(this.myUserName);    
      }, 5000),     

再次更正一下, 原先我无法访问, 只是我的书写格式不正确,
只要按上面格式, 就可以直接访问 this里面的变量了.

  • 1***@qq.com (作者)

    其中 kStrUtils是我的自已的单元名, 你要适应更改一下

    2023-02-14 21:36

要回复问题请先登录注册