首页 > 解决方案 > Vue js如何防止按钮连续点击两次

问题描述

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

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

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

在 Vue 文档事件修饰符 中我发现.stop

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

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

标签: javascriptvue.jsvuejs2vue-directives

解决方案


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

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

<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>

推荐阅读