zoukankan      html  css  js  c++  java
  • element ui中动态添加的表单进行验证

    项目中有一项表单是需要动态添加的,但是动态添加的表单,验证规则也需要动态添加。

    官网中的例子:

     代码如下:

    注意事项在代码中红色注释

    <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic"> //这里的model一定要用 :model 形式 而不是 v-model
      <el-form-item
        prop="email"
        label="邮箱"
        :rules="[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]"
      >
        <el-input v-model="dynamicValidateForm.email"></el-input>
      </el-form-item>
      <el-form-item
        v-for="(domain, index) in dynamicValidateForm.domains"
        :label="'域名' + index"
        :key="domain.key"
        :prop="'domains.' + index + '.value'"  //这里的prop绑定的时候一定要从你v-for循环下的对象中。  prop属性后面也就是你要验证的地方。
        :rules="{
          required: true, message: '域名不能为空', trigger: 'blur'
        }"
      >
        <el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
        <el-button @click="addDomain">新增域名</el-button>
        <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <script>
      export default {
        data() {
          return {
            dynamicValidateForm: {
              domains: [{
                value: ''
              }],
              email: ''
            }
          };
        },
        methods: {
          submitForm(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                alert('submit!');
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          },
          removeDomain(item) {
            var index = this.dynamicValidateForm.domains.indexOf(item)
            if (index !== -1) {
              this.dynamicValidateForm.domains.splice(index, 1)
            }
          },
          addDomain() {
            this.dynamicValidateForm.domains.push({
              value: '',
              key: Date.now()
            });
          }
        }
      }
    </script>

    具体可参考官网:https://element.eleme.cn/#/zh-CN/component/form

  • 相关阅读:
    [Linux] Chmod 改变权限
    [linux命令]基本命令
    [Linux命令] 查看目录大小du
    [Linux命令]格式化mkfs
    在VMWare下的Linux切换
    .net的MSMQ异步调用
    CASSINI源代码分析
    [Wix] RadioButton与ListItem的属性要改掉了
    如何快速生成Insert数据插入语句?
    撕纸
  • 原文地址:https://www.cnblogs.com/shiyiersan/p/13501450.html
Copyright © 2011-2022 走看看