vue3第三十六节(自定义插件之自定义指令)防重指令

引言:自定义指令,我们可以通过插件的形式进行全局注册: 例如:在提交按钮请求接口时候,为了防止重复提交,而导致的请求资源浪费,或者是新增提交时候,防止新增相同的数据。 我们的全局注册自定义防重按钮

1、编写防重指令插件

// plugins/myDirective/index.ts 文件

typescript 复制代码
import { App, AppContext} from 'vue'
export default {
	// 通过install 方法
    install(app:App, config:AppContext) {
        app.directive('MyRepeat', {
            mounted: function(el: HTMLButtonElement, binding: any) {
                el.addEventListener('click',() => {
                    if (!el.disabled) {
                        el.disabled = true
                        let timer: number | undefined = setTimeout(():void => {
                            el.disabled = false
                            clearTimeout(timer)
                            timer = undefined
                        }, binding.value || 2000)
                    }
                })
            }
        })
    }
}

注意 :在定义自定义指令时候,我们通常用到的,只有 mounted 和 updated 生命钩子函数;详情参考自定义指令

2、引入自定义插件

// main.ts

javascript 复制代码
import { createApp } from 'vue'
import myDirective from './plugins/myDirective/index.ts'
const app = createApp(App)
// 全局注册 指令 myDirective
app.use(myDirective)

3、使用自定义插件

通过 v-xx 写法 直接给按钮添加新的指令即可 v-myRepeat

xml 复制代码
<template>
<el-button v-myRepeat @click="handleChangeNum">自定义插件指令-{{num}}</el-button>
</template>
<script setup>
import { ref, onActivated, inject, getCurrentInstance } from "vue"
const num = ref(0)
const handleChangeNum = () => {
  num.value = num.value + 1
  console.log('===', num.value)
}
</script>
相关推荐
掘金安东尼15 分钟前
前端周刊第421期(2025年7月1日–7月6日)
前端·面试·github
摸鱼仙人~18 分钟前
深入理解 classnames:React 动态类名管理的最佳实践
前端·react.js·前端框架
未来之窗软件服务20 分钟前
chrome webdrive异常处理-session not created falled opening key——仙盟创梦IDE
前端·人工智能·chrome·仙盟创梦ide·东方仙盟·数据调式
kymjs张涛20 分钟前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
玲小珑24 分钟前
Next.js 教程系列(十)getStaticPaths 与动态路由的静态生成
前端·next.js
天天鸭30 分钟前
写个vite插件自动处理系统权限,降低99%重复工作
前端·javascript·vite
蓝婷儿35 分钟前
每天一个前端小知识 Day 23 - PWA 渐进式 Web 应用开发
前端
无奈何杨44 分钟前
CoolGuard风控中新增移动距离和移动速度指标
前端·后端
恋猫de小郭1 小时前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
江城开朗的豌豆1 小时前
Vue-router方法大全:让页面跳转随心所欲!
前端·javascript·vue.js