随笔 - 754  文章 - 0 评论 - 33 阅读 - 135万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 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();
          }
        })
      },
复制代码

 



感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接
posted on   周文豪  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示