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>
相关推荐
菜泡泡@35 分钟前
仓库地图vue-grid-layout
前端·javascript·vue.js
u***u6853 小时前
React环境
前端·react.js·前端框架
X***E4633 小时前
前端数据分析应用
前端·数据挖掘·数据分析
4***14903 小时前
React社区
前端·react.js·前端框架
LFly_ice3 小时前
学习React-24-路由传参
前端·学习·react.js
Lhuu(重开版4 小时前
CSS:动效布局动画
前端·css
Q***K554 小时前
前端构建工具
前端
laocooon5238578864 小时前
创建了一个带悬停效果的“我的个人主页“按钮
前端
2013编程爱好者5 小时前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
小满zs6 小时前
Next.js第十一章(渲染基础概念)
前端