在uniapp的节流函数

为了解决同一个人连续多次的点击同一个事件会造成的问题,js解决的方法有防抖和节流,防抖和节流都是在一定的时间上控制次数

节流是在定义的时间内连续点击多次事件,只会执行一次

在uniapp的工具文件夹utils中写一个throttle.js

内容如下

// 节流函数
export function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }
    let _lastTime = null
    // 返回新的函数
    return function() {    
        let _nowTime = +new Date()    
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments) //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}

module.exports = {
  throttle: throttle
}

绑定点击事件

<button type="default" @click="goLogin">登录</button>

然后在页面当中引用

import   { throttle } from "@/utils/throttle.js"

在method如下使用

goLogin:throttle(function(){
	  	this.login()
	},1000),
login(){
 console.log('login')
} 

  

 

posted @ 2022-04-01 15:12  whiteWaiter  阅读(981)  评论(0编辑  收藏  举报