為了解決同一個人連續多次的點擊同一個事件會造成的問題,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') }