0
点赞
收藏
分享

微信扫一扫

解决按钮点击后长按回车无限触发点击事件问题


思路:

包一层 UI 库的 button,在里面监听 onkeydown 和 onkeyup,用 flag 阻止长按回车一直触发。

然后在项目全局重新注册 ​​el-button​​ 覆盖掉UI内的按钮组件。

优点


即开即用,将组件添加到项目内,引入注册即可。也不会阻止第一次回车触发的点击事件,保留原有逻辑。不需要改项目中的原​​button​​代码。

使用(Element-UI)

// main.js

import DDButton from '@/components/button.vue';

// 覆盖 element button 解决点击按钮后,长按回车无限触发点击事件问题
Vue.component('el-button', DDButton);

组件封装

<template>
<el-btn
ref="btn"
:type="type"
:size="size"
:icon="icon"
:nativeType="nativeType"
:loading="loading"
:disabled="disabled"
:plain="plain"
:autofocus="autofocus"
:round="round"
:circle="circle"
@click="handleClick"
>
<slot></slot>
</el-btn>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Button } from 'element-ui';
@Component({
components: {
elBtn: Button,
},
})
export default class DDButton extends Vue {
@Prop({ default: 'default', type: String }) type?: string;
@Prop({ default: '', type: String }) size?: string;
@Prop({ default: '', type: String }) icon?: string;
@Prop({ default: 'button', type: String }) nativeType?: string;
@Prop({ type: Boolean }) loading?: boolean;
@Prop({ type: Boolean }) disabled?: boolean;
@Prop({ type: Boolean }) plain?: boolean;
@Prop({ type: Boolean }) autofocus?: boolean;
@Prop({ type: Boolean }) round?: boolean;
@Prop({ type: Boolean }) circle?: boolean;

handleClick(evt: any) {
this.$emit('click', evt);
}
handleKeydown() {
let flag = false;
const btn = this.$refs.btn as any;
if (!btn?.$el) return;
btn.$el.onkeydown = (e: any) => {
if (e?.keyCode === 13) {
if (!flag) {
flag = true;
} else {
return false;
}
}
};
btn.$el.onkeyup = (e: any) => {
if (e?.keyCode === 13) {
flag = false;
}
};
}
mounted() {
this.handleKeydown();
}
}
</script>

码字不易,觉得有帮助的小伙伴记得点个赞鼓励下~

解决按钮点击后长按回车无限触发点击事件问题_button

扫描上方二维码关注我的订阅号~



举报

相关推荐

0 条评论