element 虽好用, 但使用不当也容易导致一些奇怪的问题
今天讲讲 “对话框中重复提交表单” 的问题
问题描述
有个对话框, 框里有个异步提交按钮
没加锁
可用重复点击
加了锁 :loading=“queryParamsLock”
在对话框消失前还能点击
因为 “消失” 是一个动画
网络上建议在 el-dialog.open 事件里解锁
请求结束前, 重新打开对话框能点击
解决方法
把加锁条件改成这样
:loading=“queryParamsLock || !dialogVisible”
原理
因为提交按钮 :loading 设了 queryParamsLock || !dialogVisible
所以 !(queryParamsLock || !dialogVisible) 是按钮可点条件
计算得 !queryParamsLock && dialogVisible 按钮可点
queryParamsLock | dialogVisible | 状态 | |
---|---|---|---|
目标值 | false | true | 按钮可点 |
打开对话框前 | false | false | 禁 |
打开对话框 | false | true | 可用 |
异步请求 | true | true | 禁 |
异步结束 && 关闭对话框 | false | false | 禁 |
demo
插件请自行补全
<html>
<head>
<meta charset="utf-8">
<title>el dialog 重复提交修复方案</title>
<link rel="stylesheet" href="../jvw/element-ui/element-ui@2.4.0/element-ui.2.4.0.css">
</head>
<body>
<div id="swq">
<App></App>
</div>
<script type="text/x-template" id="App-template">
<div>
<el-button @click="dialogVisible = true">点击打开 Dialog</el-button>
<el-dialog title="提示" :visible.sync="dialogVisible">
<div>这是一段信息</div>
<div slot="footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="queryParamsSubmit" :loading="queryParamsLock || !dialogVisible">不可重复提交</el-button>
<el-button type="primary" @click="queryParamsSubmit" :loading="queryParamsLock">对话框消失前可提交</el-button>
<el-button type="danger" @click="queryParamsSubmit">可重复提交</el-button>
</div>
</el-dialog>
</div>
</script>
<script src="../jvw/vue/vue@2.5.16.js"></script>
<script src="../jvw/element-ui/element-ui@2.4.0/1element-ui.2.4.0.js"></script>
<script type="text/javascript">
var App = {
template: "#App-template",
data: function() {
return {
dialogVisible: false,
queryParamsLock: false,
}
},
methods: {
// 提交对话框
queryParamsSubmit() {
console.log("请求")
// validate 通过
if(this.queryParamsLock) {
return
}
// 上锁
this.queryParamsLock = true
// 请求
setTimeout(() => {
// 请求结束
// 关闭
this.dialogVisible = false
// 解锁
this.queryParamsLock = false
}, 1000)
},
},
};
var vu = new Vue({
el: "#swq",
components: {
App: App,
},
})
</script>
</body>
</html>
end