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