按钮防止短时间内多次点击的自定义指令
这段代码定义了一个Vue指令,名为preventReClick
它的作用是防止用户在2秒内重复点击某个按钮。
当用户点击按钮时,按钮的disabled属性会被设置为true,并且按钮的背景颜色会被设置为#ccc,边框会被设置为none,鼠标样式也会被设置为not-allowed。
2秒后,按钮会被重置,disabled属性会被设置为false,背景颜色被设置为#002FA8,边框被设置为1px solid #002FA8,鼠标样式也会被设置为pointer。
import Vue from 'vue'
const preventReClick = Vue.directive('preventReClick',{
inserted: function(el, binding, vNode, oldVnode){
el.addEventListener('click', () => {
if(!el.disabled){
el.disabled = true
el.style.backgroundColor = '#ccc'
el.style.border = 'none'
el.style.cursor = 'not-allowed'
setTimeout(() => {
el.disabled = false
el.style.backgroundColor = '#002FA8'
el.style.border = '1px solid #002FA8'
el.style.cursor = 'pointer'
}, 2000)
}
})
}
})
export default {
preventReClick
}
使用方法也很简单
在main.js里引用
//防频繁点击
import preventReClick from '@/utils/directive'
Vue.use( preventReClick )
直接调用即可
<el-button v-preventReClick >确认</el-button>
两个点击事件叠加 触发子元素点击事件
业务场景
外面form-item有个一行的点击事件
里面单选框跟复选框的点击事件被覆盖
处理办法
为事件增加了阻止冒泡指令.stop ,由于el-checkbox是组件不是标签,需要在.stop后面加上.native
<el-radio-group
v-model="item.defaultValue"
@click.stop.native="()=>{}"
@input="()=>{radioBoxResponseEvent(i)}"
>
<el-radio
v-for="optItem in item.glossaryOptions"
:key="optItem.value"
:label="optItem.label"
>{{ optItem.label }}</el-radio>
</el-radio-group>