Vue实战指南:如何实现防止重复点击的指令,提升用户体验与性能

132 阅读1分钟

Vue实战指南:如何实现防止重复点击的指令,提升用户体验与性能

本文将介绍在Vue应用中如何通过自定义指令来防止重复点击行为。重复点击按钮不仅会导致用户体验下降,还可能引发意外的操作和性能问题。通过使用自定义指令,我们可以简单而优雅地解决这个问题,提升用户体验和应用性能。本文将深入讲解如何创建自定义指令,实现防止重复点击的功能,并给出一些实用的技巧和最佳实践。

你可以通过自定义指令来防止重复点击,当按钮被点击时,会检查按钮的 disabled 属性是否为 false,如果是,则将其设置为 true,并在一定时间后恢复为 false。这样,在按钮被禁用期间,再次点击按钮时将无效。你可以根据需要调整延迟时间(默认为 500毫秒)和按钮的样式。

/*
 * @Author: long
 * @Date: 2023-02-21 10:47:00
 * @LastEditTime: 2023-02-08 14:10:39
 * @LastEditors: long
 * @Description: 按钮防止重复点击指令
 */
const background = '#c1c1c1'
const color = 'black'

function setBackGround(el,isEnable,oldColorObj){
    const btnContent = el.querySelector('.v-btn__content')
    if(isEnable){
        el.style.background = oldColorObj?.oldBackground 
        el.style.color = oldColorObj?.oldColor 
        if(btnContent){
            btnContent.style.background = oldColorObj?.contentOldBackground 
            btnContent.style.color = oldColorObj?.contentOldColor 
        }
    }else{
        el.style.setProperty('background',background,'important')
        el.style.setProperty('color',color,'important')
        if(btnContent){
            btnContent.style.setProperty('background',background,'important')
            btnContent.style.setProperty('color',color,'important')
        }
    }
}

export default {
    name:'preventReClick',
    inserted(el, binding) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                //获取未禁用前的颜色
                const btnContent = el.querySelector('.v-btn__content')
                const oldColorObj = {
                    oldBackground: el.style.backgroundColor ,
                    oldColor: el.style.color,
                    contentOldBackground: btnContent?.style.backgroundColor,
                    contentOldColor: btnContent?.style.color
                }
                el.disabled = true;
                el.style.setProperty('pointer-events','none')
                setBackGround(el,false)
                setTimeout(() => {
                    el.disabled = false;
                    el.style.setProperty('pointer-events','auto')
                    setBackGround(el,true,oldColorObj)
                }, binding.value || 500)
            }
        })
    }
  }

将上述定义的指令注册为全局指令:

import preventReClick from './preventReClick '
Vue.filter('preventReClick', preventReClick )

使用:

<v-btn v-preventReClick class="mr-2 px-2" @click="clickImport" >按钮</v-btn>