Vue JS如何防止按钮连续两次被点击

Pat*_*han 4 javascript vue.js vuejs2 vuejs-directive

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

如果我进一步解释。两次单击之间的间隔应该很小。

如何使用vue js实现此目的?

在Vue docs 事件修饰符中, 我发现.stop

<button @click.stop="myFunction">Increase</button>
Run Code Online (Sandbox Code Playgroud)

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

And*_*vin 6

不,.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>
Run Code Online (Sandbox Code Playgroud)