在vue框架中防止用户重复提交表单的方法
在互联网应用中有效地阻止用户重复点击操作可以极大地提高系统的安全性和稳定性。为此,好友封装了一个专门用于提交表单和下载文件的按钮组件,为方便描述姑且称之为“防抖按钮”。
“防抖按钮”的实现原理简单来说,当用户点击按钮提交表单或下载文件之后,当前按钮将处于禁用状态,等待服务器响应结束后,恢复该按钮的可用状态。
在当前流行的vue框架中,实现其功能的具体方法是在父组件中引入“防抖按钮”,并在“防抖按钮”的:click属性中设置发送请求的方法。当“防抖按钮”被点击后,“防抖按钮”中@click监听器绑定的方法会将按钮的:loading属性值修改为true,并执行父组件中设置的ajax方法,在函数未获取到服务器响应之前,该按钮一直处于不可用状态。待函数接收到服务器响应后,@click监听器绑定的方法会将按钮的:loading属性值修改为false,即恢复按钮的可用状态。
以下是实际应用中的例子,供大家参考。
父组件:
<style lang="less" scoped>
</style>
<template>
<div id="app">
<!-- fn为发送请求的方法 -->
<ajax-btn :click="fn">请求</ajax-btn>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {}
},
methods: {
async fn() {
console.log('开始')
return new Promise(resolve => {
// 模拟服务器响应(1秒钟后往下执行)
setTimeout(() => {
console.log('完成')
resolve()
}, 1000)
})
}
},
}
</script>
子组件:
<template>
<el-button
@click="startLoading"
:autofocus="autofocus"
:circle="circle"
:round="round"
:plain="plain"
:type="type"
:size="size"
:native-type="nativeType"
:loading="loading">
<slot></slot>
</el-button>
</template>
<script>
const types = ['primary','success','warning','danger','info','text']
const sizes = ['medium','small','mini']
const nativeTypes = ['button','submit']
export default {
name: 'ajaxBtn',
data() {
return {
loading: false
}
},
props: {
click: { type: Function, required: true, },
autofocus: { type: Boolean, default: false },
circle: { type: Boolean, default: false },
round: { type: Boolean, default: false },
plain: { type: Boolean, default: false },
type: {
type: String,
validator: (value) => (types.indexOf(value) !== -1)
},
size: {
type: String,
validator: (value) => (sizes.indexOf(value) !== -1)
},
nativeType: {
type: String,
validator: (value) => (nativeTypes.indexOf(value) !== -1)
}
},
methods: {
// @click事件监听器绑定的方法
async startLoading() {
if (this.loading) return
this.loading = true
await this.click()
this.loading = false
}
}
}
</script>
如需详细源码,请点这里