How to reset a specific form field with element-ui

4.9k Views Asked by At

I'm currently learning VueJS and I'm using the Element-UI framework. What I would like is that if there is a validation error when submitting the login form I want to clear the password field.

According to the Element-UI documentation the form-item has a resetField method but I do not know how to access the form-item programatically. Here is my form code.

<el-form
    ref="login"
    :model="login"
    :rules="loginRules"
    label-width="120px"
    label-position="top"
    v-if="pageMode == 'login'"
    @keydown.native="loginError = false"
    @submit.native.prevent="validateLogin('login')"
  >
    <el-form-item label="Email Address:" prop="email">
      <el-input v-model="login.email"></el-input>
    </el-form-item>
    <el-form-item label="Password:" prop="password">
      <el-input
        type="password"
        v-model="login.password"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item style="text-align:center;">
      <el-button native-type="submit" type="primary">Login</el-button>
      <el-button type="primary" @click="resetForms('login')"
        >RESET</el-button
      >
    </el-form-item>
  </el-form>

and here is my loginUser function

async validateLogin(formName) {
  try {
    let response = await this.$auth.loginWith("local", {
      data: this.login
    });
  } catch (err) {
    //handle error
    this.notiColor = "red";
    this.loginError = true;

    this.$refs[formName].password.resetField();  /// THIS DOES NOT WORK
  }
},

As you can see I tried using the this.$refs[formName].password.resetField() but it didn't work I got a "Cannot read property 'resetField' of undefined.

Any help would be greatly appreciated.

Regards

CES

1

There are 1 best solutions below

0
On BEST ANSWER

If you just want to empty the field it is easier to access to field directly:

this.password = null

If you want to clear the password field and reset the validation message of the password field it is:

this.$refs[formName].fields.find((f) => f.prop == "password").resetField()