【问题标题】:Vue js how to prevent button clicked on two times continuously [duplicate]Vue js如何防止按钮连续点击两次[重复]
【发布时间】:2019-07-06 19:44:36
【问题描述】:

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

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

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

在 Vue 文档中 Event modifiers 我找到了.stop

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

这能达到我想要的效果吗?

【问题讨论】:

  • 没有 click.stop 只会阻止您的事件传播到父元素。
  • 您可以在单击按钮后将disabled 属性添加到按钮。然后在逻辑完成后删除disabled 属性。
  • 在使用 setTimeout 执行 myFunction 之前禁用按钮一段时间如何?这是检查jsfiddle.net/vitragparekh/9k76oh23/6的小提琴

标签: javascript vue.js vuejs2 vue-directives


【解决方案1】:

不,.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>

【讨论】:

    【解决方案2】:

    正如其他人所说,.stop 修饰符只会阻止事件传播 DOM。要获得您正在寻找的结果,您可以查看 Lodash 的 debounce 方法..

    _.debounce(func, [wait=0], [options={}])
    

    创建一个去抖动函数,该函数延迟调用func,直到自上次调用去抖动函数后等待毫秒过去。

    这是一个简单的例子..

    new Vue({
      el: "#app",
      data: {
        counter: 0
      },
      methods: {
        myFunction() {
          this.counter++
        },
      },
      created() {
        this.debouncedMyFunction = debounce(this.myFunction, 300, {
          leading: true,
          trailing: false
        })
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.4/vue.min.js"></script>
    <script src="https://unpkg.com/lodash.debounce@4.0.8/index.js"></script>
    
    <div id="app">
      <button @click.stop="debouncedMyFunction">Increase</button>
      <p>
        {{ counter }}
      </p>
    </div>

    leading 选项指定为true 并将trailing 指定为false 将导致函数在超时的前沿而不是尾端被调用。您可以以毫秒为单位将超时值从 300 更改为所需的值。

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 2013-05-18
      • 2011-09-02
      • 2014-11-13
      • 1970-01-01
      • 2020-09-09
      • 2014-12-11
      • 1970-01-01
      相关资源
      最近更新 更多