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>
相关推荐
用户86022504674722 分钟前
从入门到进阶的 React Native 实战指南
android·前端
贵州数擎科技有限公司3 分钟前
雨滴特效的 Three.js 实现
前端·three.js
问心无愧05133 分钟前
ctf show web入门98
android·前端·笔记
irving同学462383 分钟前
Drizzle ORM + PostgreSQL + Hono 学习笔记
前端·后端
明豆4 分钟前
HTTPS / TLS 1.3 深度解析 — Web 安全传输协议生产实战
前端·安全·https
Linsk4 分钟前
Rollup 官方插件 @rollup/plugin-inject 详解
前端·rollup.js·前端工程化
2601_958492555 分钟前
Performance Audit of Paper Boats Racing - HTML5 Racing Game
前端·html·html5
Aolith7 分钟前
从0到1实现帖子上传图片:我是如何复用头像上传逻辑的
vue.js·图片资源
irving同学462387 分钟前
TypeScript 后端入门全景:Hono + Zod + Drizzle + PostgreSQL
前端·后端
一致性7 分钟前
项目总结:桌宠(Desktop Pet)
前端