Vue js如何防止按钮连续点击两次 [英] Vue js how to prevent button clicked on two times continuously

查看:78
本文介绍了Vue js如何防止按钮连续点击两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,用户可以根据需要多次单击该按钮.但是当用户点击按钮时,他可能会不小心点击两次,这种情况下第二次点击应该被代码阻止.

I have a button, user can click the button more than one time if he want. But when the user click the button, he might accidentally click twice, in such cases second click should be blocked by the code.

如果我进一步解释.它们应该是两次点击之间的小延迟.

If I further explain. They should be a small delay between two clicks.

我如何使用 vue js 实现这一点?

How do I achieve this using vue js?

在 Vue 文档中 事件修饰符我找到了 .stop

In Vue docs Event modifiers I found .stop

<button @click.stop="myFunction">Increase</button>

这能完成我想要的工作吗?

Does this do the job what I want?

推荐答案

不,.stop 修饰符不能解决您的问题.该修饰符的作用是防止事件传播(它相当于 stopPropagation() 在计划 JavaScript)

No, the .stop modifier does not solve your problem. What that modifier does is to prevent event propagation (it is equivalent to stopPropagation() in plan JavaScript)

您可以使用 .once 修饰符来防止在第一个事件之后发生任何其他事件.但是,如果您想允许多次点击,但它们之间有延迟,您可以执行以下操作:

You could use the .once modifier to prevent any further events after the first one. However, if you want to allow multiple clicks, but have a delay between them, you could do something like this:

<template>
    <button :disabled="disabled" @click="delay">Increase</button>
</template>

<script>
  export default {
    data () {
      return {
        disabled: false,
        timeout: null
      }
    },
    methods: {
      delay () {
        this.disabled = true

        // Re-enable after 5 seconds
        this.timeout = setTimeout(() => {
          this.disabled = false
        }, 5000)

        this.myFunction()
      },
      myFunction () {
        // Your function
      }
    },
    beforeDestroy () {
     // clear the timeout before the component is destroyed
     clearTimeout(this.timeout)
    }
  }
</script>

这篇关于Vue js如何防止按钮连续点击两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆