以阻止连续点击为例
vue2.x 自定义指令
main.js
import Vue from 'vue'
Vue.directive('preventContinuityClick', {
inserted: function (el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 3000)
}
})
}
});
vue3.x 自定义指令
main.js
import { createApp } from 'vue'
... 省略代码
const app = createApp({});
app.directive('preventContinuityClick', {
mounted(el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 3000)
}
})
}
})
组件调用方法一样
默认
<el-button type="primary" @click="add" v-preventContinuityClick>提交</el-button>
传参
<el-button type="primary" @click="add" v-preventContinuityClick="5000">提交</el-button>