关于javascript:Vue中函数节流

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>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理