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>
相关推荐
前端初见几秒前
React 开发实战全攻略:从基础到项目实战(面向 Vue 开发者)
javascript·vue.js·react.js
右耳朵猫AI2 分钟前
React技术周刊 2026年第14周
前端·react.js·前端框架
ym_xixi4 分钟前
《类和对象》—— 构造函数与析构函数总结
前端·c++·算法
csj507 分钟前
前端基础之《React(8)—webpack简介-其他配置》
前端·react.js
恋猫de小郭15 分钟前
AndroidX 将引入有全新 AppState ,用于管理 Compose 状态
android·前端·flutter
别问,问就是菜鸡19 分钟前
阿里云效前端流水线自动化部署
前端·阿里云·自动化·持续部署
燐妤20 分钟前
前端HTML编程4:深入学习CSS
前端·学习·html
2301_8163743324 分钟前
服务访问的用户认证
前端·网络
XS03010624 分钟前
从浏览器到互联网的完整数据流
前端·数据库·servlet·交互
hhb_61830 分钟前
MATLAB数值计算与数据可视化核心技术梳理及实战应用案例解析
前端