对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promise
问题代码:
save(){ console.log(that.pos.indexName) console.log(that.pos.indexCode) this.$refs['from'].validate((valid) => { if (valid) { debugger that.pos.indexName = that.pos.indexName + "_" +that.pos.indexNum; that.pos.indexCode = that.pos.indexCode + String(that.pos.indexNum).padStart(4, '0'); var pos = Object.assign({},that.pos); console.log(pos) this.$emit("loadLines",pos); this.closeDialog(); } }) },
情景再现:save方法中,第一行和第二行代码都有值,但是在回调方法内部,that.pos.indexName和that.pos.indexCode的确没有值。后来才得知由于validate方法是异步的,回调函数内部如果使用全局变量,一旦其他地方修改了全局变量,that.pos.indexName和that.pos.indexCode的值也会被修改。
没想到后面的closeDialog方法确实修改了全局变量that.pos.indexName和that.pos.indexCode,如下所示:
resetTemp() { this.pos.indexName = ""; this.pos.indexCode = null; }, closeDialog() { this.resetTemp() this.$nextTick(() => { this.$refs['from'].clearValidate(); this.dialogFormVisible = false; }) }
正是由于closeDialog方法对全局变量that.pos.indexName和that.pos.indexCode进行了置空,导致我认为回调函数内没有值。
正确的做法是回调函数内使用局部变量,而不是全局变量,即使发生其他地方修改全局变量的情况,也不会影响到回调函数内的值。
save(){ let indexName = that.pos.indexName let indexCode = that.pos.indexCode this.$refs['from'].validate((valid) => { if (valid) { that.pos.indexName = indexName + "_" +that.pos.indexNum; that.pos.indexCode = indexCode + String(that.pos.indexNum).padStart(4, '0'); var pos = Object.assign({},that.pos); this.$emit("loadLines",pos); this.closeDialog(); } }) },
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!