问题:两个表单切换,分别使用不同校验规则,校验规则失效

解决思路:1.切换时使用resetField对该表单项进行重置,将其值重置为初始值并移除校验结果

问题本质:即使两个表单绑定的值不同,但是浏览器在解析时,先解析第一个表单,此时表单上是没有绑定ref,之后再解析第二个表单时,浏览器发现这它的prop和第一个表单的prop一样,所以就认为这两个表单是同一个表单,就没有重新渲染,而ref本身是作为渲染结果被创建的,所以第二个表单没能成功绑定ref,验证就无法生效。

loginTypeFlag() {
      if (this.loginFlag) {
        this.passwordLogin = "密码登录";
        this.phoneLogin = "手机登录";
        this.$refs['phoneRef'].resetFields();
      } else {
        this.passwordLogin = "手机登录";
        this.phoneLogin = "密码登录";
        this.$refs['loginRef'].resetFields();
      }
    },
     // 切换登录方式
    loginTypeSubmit() {
      this.loginFlag = !this.loginFlag;
      this.loginTypeFlag();
    },

2.分别给表单加key值进行区分

<el-form key="loginFormKey" :model="passwordForm" :rules="loginRules" ref="loginRef" v-if="loginFlag">
            <el-form-item prop="number">
              <el-input
                v-model="passwordForm.number"
                placeholder="请输入账号"
                prefix-icon="el-icon-user"
                size="small"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" class="passwordSty">
              <el-input
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-unlock"
                @keyup.enter.native="submitForm('loginRef')"
                size="small"
              ></el-input>
            </el-form-item>
            <el-form-item class="forgetPassword">
              <p>忘记密码</p>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('loginRef')" class="loginBtn">立即登录</el-button>
            </el-form-item>
          </el-form>
          <!-- 手机号登录 -->
          <el-form key="phoneKey" :model="phoneForm" :rules="phoneRules" ref="phoneRef" v-else>
            <el-form-item prop="phone">
              <el-input
                v-model="phoneForm.phone"
                placeholder="请输入手机号"
                prefix-icon="el-icon-mobile-phone"
                size="small"
                class="numberBox"
              ></el-input>
              <el-button :disabled="codeDisabled" class="getNumeber" type="primary" size="small" @click="getCaptcha">{{codeMsg}}</el-button>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input
                v-model="phoneForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="el-icon-edit"
                size="small"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitPhoneForm('phoneRef')" class="loginBtn">立即登录</el-button>
            </el-form-item>
          </el-form>
Logo

前往低代码交流专区

更多推荐