对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 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 2024-06-05 17:28  周文豪  阅读(9)  评论(0编辑  收藏  举报