In order to achieve a unified method of preventing repeated click triggers, I checked the online data and showed:
One, introduce preventReClick.js
import Vue from 'vue'
const preventReClick = Vue.directive('preventReClick', {
inserted: function (el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 3000)
}
})
}
});
export { preventReClick }
Second, introduce in main.js:
import preventReClick from './store/preventReClick' // prevent multiple clicks, repeated submission
Three, the implementation method:
<div @click="click" v-preventReClick="5000">测试多次重复请求</div>
Important point: However, tests have shown that it is only effective for el-buttons, and has no effect for ordinary divs or self-encapsulated components, because disabled normally does not prevent the click effect of @click.
To this end, the following improvements are made:
import Vue from 'vue'
const preventReClick = Vue.directive('preventReClick', {
inserted: function(el, binding) {
el.addEventListener('click', (e) => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, binding.value || 1000)
} else { // disabled为true时,阻止默认的@click事件
e.preventDefault()
e.stopPropagation()
}
}, true)
}
});
export { preventReClick }
The focus is on the last parameter, addEventListener(event, function, useCapture);
the default value is false, that is, bubbling transfer, when the value is true, the event uses capture transfer.