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