一个Vue表单提交防抖的实用例子
Vue表单提交防抖也叫防重复提交
目标效果:
上代码:
vue init webpack demo 用vue-cli指令简单快速构建一个vue项目,过程和结构不说了,编辑helloword.vue,删掉vue示例代码(app.vue根元素页面上有个大logo记得也删掉)
首先新增一个js文件,用来放防抖等工具方法。
src/utils/public.js
// 防抖 export const Debounce = (fn, t) => { let delay = t || 500 let timer return function () { let args = arguments; if (timer) { clearTimeout(timer) } let callNow = !timer timer = setTimeout(() => { timer = null }, delay) if (callNow) fn.apply(this, args) } }
在helloworld.vue文件引入Debounce
import { Debounce } from '@/utils/public'
helloword.vue文件完整代码:
<template> <div class="hello"> <div class="form-wrap"> <div class="form-group"><span class="form-label">姓名</span><input type="text" v-model="fullname"></div> <div class="form-group"><span class="form-label">性别</span><input id="radio1" type="radio" v-model="sex" value="男"><label for="radio1">男</label><input id="radio2" type="radio" v-model="sex" value="女"><label for="radio2">女</label></div> <div class="form-ft"> <button @click="Submit">提交</button> </div> </div> <div class="form-res"> <h5>提交后:</h5> <p>提交次数:{{formData.count}}</p> <p>姓名:{{formData.fullname}}</p> <p>性别:{{formData.sex}}</p> </div> </div> </template> <script> import { Debounce } from '@/utils/public' export default { name: 'HelloWorld', data () { return { fullname: '', sex: '', formData: { fullname: '', sex: '', count: 0 } } }, methods: { Submit: Debounce(function () { this.formData.fullname = this.fullname; this.formData.sex = this.sex; this.formData.count++ }, 3000) } } </script> <style lang="scss" scoped> .form-wrap { margin: 30px; border: 1px solid #eee; border-radius: 3px; width: 300px; padding: 15px; .form-group { display: flex; margin-bottom: 10px; .form-label { margin-right: 10px; } } .form-ft { text-align: center; margin-top: 20px; } } .form-res { margin: 0 30px; padding: 15px; h5 { margin-bottom: 10px; } p { margin-bottom: 5px; } } </style>
首次点击提交按钮会立即执行一次Debounce方法,后面3s内不触发事件才能继续执行。这很适合防止表单重复提交
参考文章:https://www.jianshu.com/p/c8b86b09daf0
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理