2

1.通过回调函数恢复按钮可点击(可用于限制发送http请求,即等待HTTP请求返回后执行回调恢复按钮可点击)
节流函数:

/**
按钮点击限制(自主设置可点击--函数节流)
@param {Fun} callback 回调函数
@return
*/
const btnlimit = function (callback) {
    var isDis
    return function (...arg) {
        if (!isDis) {
            isDis = true    
            callback.call(this, arg, function () {
                isDis = false
            })
        }
    }
}

使用示例:

<template>
    <button @click="onSubmit">{{value}}</button>
</template>
<script>
     export default {
        data() {
            return {
                value: '发送HTTP请求'
            }
        },
        methods: {
            onSubmit: btnlimit(function(e, callback) {   //此处必须使用function 不能使用箭头函数
                this.value += '1'
                setTimeout(()=> {
                    callback()   //此处回调执行后点击才会继续发送http请求
                }, 2000)
            })
        }
    }
</script>

2.通过设置时间恢复按钮可点击(可用于限制频繁触发的dom事件,比如onscroll事件)
节流函数:

/**
    按钮点击限制(设置时间--函数节流)
    @param {Fun} callback 回调函数
    @param {Number} time 间隔时间
*/
const btnlimit_time = function (callback, time) {
    var startTime
    return function (...arg) {
        if(!startTime){
            startTime = new Date().getTime()
            callback.call(this, arg)
        }
        if(new Date().getTime() - startTime > time){
            startTime = new Date().getTime()
            callback.call(this, arg)
        }
    }
}

使用示例:

<template>
    <button @click="onSubmitTime">{{value}}</button>
</template>
<script>
     export default {
        data() {
            return {
                value: 'dom事件'
            }
        },
        methods: {
            onSubmitTime: btnlimit_time(function(e) {   //此处必须使用function 不能使用箭头函数
                this.value += '1'
            }, 400)
        }
    }
</script>

树洞丶
11 声望1 粉丝