美文网首页
vue 防止重复点击指令

vue 防止重复点击指令

作者: JackfengGG | 来源:发表于2021-03-04 18:56 被阅读0次
    /**
     * 
     * 防止重复点击指令:v-avoid-repeat
     */
    
    export default {
        install(Vue) {
            Vue.directive('avoid-repeat', {
                inserted (el, binding) {
                    function __avoidRepeatHandler__() {
                        if (el.__clickDisabled__) return;
    
                        el.__clickDisabled__ = true;
                        el.__originalPointerEvents__ = el.style.pointerEvents;
                        el.style.pointerEvents = 'none';
                        setTimeout(() => {
                            el.__clickDisabled__ = false;
                            el.style.pointerEvents = el.__originalPointerEvents__;
                        }, binding.value || 500)
                    }
                    el.addEventListener('click', __avoidRepeatHandler__);
                    el.__avoidRepeatHandler__ = __avoidRepeatHandler__;
                },
                unbind(el) {
                    el.removeEventListener('click', el.__avoidRepeatHandler__);
                    delete el.__clickDisabled__;
                    delete el.__originalPointerEvents__;
                }
            })
        }
    }
    

    Use

    import Vue from 'vue'
    import vAvoidRepeat from '@yqb/v-avoid-repeat'
    
    Vue.use(vAvoidRepeat)
    
    <template>
        <div v-avoid-repeat @click="onClick">
        </div>
    </template>
    
    <template>
        <div v-avoid-repeat="1000" @click="onClick">
        </div>
    </template>
    

    相关文章

      网友评论

          本文标题:vue 防止重复点击指令

          本文链接:https://www.haomeiwen.com/subject/uxcvfltx.html