美文网首页
vue3 自定义指令 防止重复点击

vue3 自定义指令 防止重复点击

作者: 臭臭的胡子先生 | 来源:发表于2023-03-05 14:12 被阅读0次

1.创建 directives.js文件

// 定义防止重复点击的指令
export const preventReClick = {
    created(el, binding, vnode, prevVnode) {
        el.addEventListener('click', customClick(binding,el));
    },
    // 离开一定要销毁卸载
    unmounted(el, binding, vnode) {
        el.removeEventListener('click', customClick);
    },
};
// 逻辑封装
const customClick = (binding,el) => {
    return () =>{
        if (!el.disabled) { // 判断条件
            el.disabled = true
            setTimeout(() => {
                el.disabled = false
            },binding.arg||1000)
            // 正常触发点击事件
            binding.value();
        } else {
            // 已经成功拦截点击事件
            console.log('已经成功拦截点击事件');
        };
    };
};
//指令抛出
export const setupAuthDirective = (app) => {
  app.directive('preventReClick', preventReClick);
};
    

main.js 全局注册

import {setupAuthDirective} from './directives'

let app = createApp(App)

setupAuthDirective(app)
// 自定义指令
app.use(store).use(router).mount('#app')

页面中使用

//直接调用
<button v-custom="onClick">test按钮</button>
<button v-custom="() => onClick()">test按钮</button>
//传参
<button v-custom="() => onClickTest1 (123)">test按钮</button>
//自定义时间
<button v-custom:3000="() => onClickTest1 (123)">test按钮</button>
const onClick = () => {
    console.log('_____函数不带括号');
};

const onClickTest1 = (num: number) => {
    console.log('_____函数带括号 可传值');
};

相关文章

网友评论

      本文标题:vue3 自定义指令 防止重复点击

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