Vue表單提交防抖也叫防重複提交css
目標效果:vue
上代碼:webpack
vue init webpack demo 用vue-cli指令簡單快速構建一個vue項目,過程和結構不說了,編輯helloword.vue,刪掉vue示例代碼(app.vue根元素頁面上有個大logo記得也刪掉)web
首先新增一個js文件,用來放防抖等工具方法。vue-cli
src/utils/public.jsapp
// 防抖 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文件完整代碼:flex
<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內不觸發事件才能繼續執行。這很適合防止表單重複提交this