900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 解决按钮点击后长按回车无限触发点击事件问题

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

时间:2023-01-24 05:07:57

相关推荐

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

思路:

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

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

优点

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

使用(Element-UI)

// main.jsimport DDButton from '@/components/button.vue';// 覆盖 element button 解决点击按钮后,长按回车无限触发点击事件问题ponent('el-button', DDButton);

组件封装

<template><el-btnref="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>

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。