javascript - Vue js如何防止按钮连续点击两次
问题描述
我有一个按钮,用户可以根据需要多次单击该按钮。但是当用户点击按钮时,他可能不小心点击了两次,在这种情况下,第二次点击应该被代码阻止。
如果我进一步解释。它们应该是两次点击之间的小延迟。
如何使用 vue js 实现这一点?
在 Vue 文档事件修饰符
中我发现.stop
<button @click.stop="myFunction">Increase</button>
这能完成我想要的工作吗?
解决方案
不,.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>
推荐阅读
- c# - 在 C# 中运行命令没有给出任何输出
- jquery - 处理多元素问题的事件
- c++ - 来自 QVariantList 的 std::function 的通用调用
- ios - 以不同的时间重复通知
- python - 尽管文件存在,但从 Python 中找不到文件
- javascript - 将结果放入变量中
- firebase - Fabric 不允许我链接我的 Firebase 应用
- c# - 使用 Json.Net 序列化对象列表而不是单个对象时出现类型信息
- node.js - 我们可以在服务器端获取谷歌分析报告,而不重定向到谷歌页面并要求登录吗?
- android - 如何在滚动视图周围显示带有 Imageview 的 Linearlayout?