清除表單驗證的問題:需要加nextTick方法

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>表單驗證</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<body>
  <div id="app">
    <el-button @click="openDialogOne">打開彈出框1</el-button>
    <el-button @click="openDialogTwo">打開彈出框2</el-button>
    <el-dialog title="彈出框" :visible.sync="dialogVisible" width="30%">
      <el-form :model="myModel" ref="myForm" label-width="120px">
        <el-form-item label="表單1" prop="name1" v-if="showed == 'one'"
          :rules="[{required: true, message: '請輸入2位數', trigger: ['blur', 'change']},{validator: checkThree, trigger: ['blur', 'change']}]">
          <el-input type="number" v-model="myModel.name1"></el-input>
        </el-form-item>
        <el-form-item label="表單2" prop="name2" v-else
          :rules="[{required: true, message: '請輸入3位數', trigger: ['blur', 'change']},{validator: checkThree, trigger: ['blur', 'change']}]">
          <el-input type="number" v-model="myModel.name2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">關閉</el-button>
        <el-button type="primary" @click="dialogVisible = false">確定</el-button>
      </span>
    </el-dialog>
  </div>
  <script>
    new Vue({
      el: "#app",
      data: {
        showed: 'one',
        dialogVisible: false,
        myModel: {
          name1: '1',
          name2: '2'
        }
      },
      methods: {
        //驗證
        checkThree(rule, value, callback) {
          var reg = /^\d{3}$/;
          if (!reg.test(value)) {
            callback(new Error("請輸入3位數"));
          } else {
            callback();
          }
        },
        //打開dialog
        openDialogOne() {
          this.showed = 'one';
          this.dialogVisible = true;
        },
        openDialogTwo() {
          this.showed = 'two';
          this.dialogVisible = true;
          // 清除表單最好寫在最後、且寫在$nextTick方法裏
          this.$nextTick(() => {
            this.$refs['myForm'].clearValidate();
          })
        }
      }
    })
  </script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章