Element-ui中 表单(Form)校验的几种形式 及 表单嵌套表格含上传(Upload)组件的综合案例

勤奋不是嘴上说说而已,而是实际的行动,在勤奋的苦度中持之以恒,永不退却。业精于勤,荒于嬉;行成于思,毁于随。在人生的仕途上,我们毫不迟疑地选择勤奋,她是几乎于世界上一切成就的催产婆。只要我们拥着勤奋去思考,拥着勤奋的手去耕耘,用抱勤奋的心去对待工作,浪迹红尘而坚韧不拔,那么,我们的生命就会绽放火花,让人生的时光更加的闪亮而精彩。

导读:本篇文章讲解 Element-ui中 表单(Form)校验的几种形式 及 表单嵌套表格含上传(Upload)组件的综合案例,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

1. Element-ui中 表单(Form)校验的几种形式

1.1 基础 / 自定义

在 el-form 上绑定 rules,rlues为校验规则,在 el-form-item 上绑定对应的prop;
自定义规则,validator:checkAge,自定义规则的函数。
详细的可查看 element 文档 http://element-cn.eleme.io/#/zh-CN/component/form

<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item label="活动名称" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input v-model.number="ruleForm.age"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>  
</template>

<script>
var checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('年龄不能为空'));
  }
  if (!Number.isInteger(value)) {
    callback(new Error('请输入数字值'));
  } else {
    if (value < rule.max_age) {
      callback(new Error('必须年满18岁'));
    } else {
      callback();
    }
  }
};

export default {
  data() {
    return {
      ruleForm: {
        name: '',
        age:''
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        age: [
          {max_age:18, validator: checkAge, trigger: 'blur' }// checkAge自定义规则函数
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!')
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

1.2 行间校验

<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
  <el-form-item
    label="年龄"
    prop="age"
    :rules="[
      { required: true, message: '年龄不能为空'},
      { type: 'number', message: '年龄必须为数字值'}
    ]">
    <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  </el-form-item>
</el-form>  

1.4 行间自定义校验

<template>
  <el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
    <el-form-item
      label="年龄"
      prop="age"
      :rules="[
        {max_age:18, validator: checkAge, trigger: 'blur' }
      ]">
      <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return{}
  },
  methods: {
    checkAge(rule, value, callback){
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        if (value < rule.max_age) {
          callback(new Error('必须年满18岁'));
        } else {
          callback();
        }
      }
    },
  }
}
</script>

1.5 行间循环自定义校验

关键代码 :prop=”domains.${index}.value“,这是 Element-ui 规定的格式,渲染后的结果为:domains.1.value。

<template>
  <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px">
    <el-form-item
      v-for="(item, index) in dynamicValidateForm.domains"
      :key="item.index"
      :label="'域名' + index"
      :prop="`domains.${index}.value`"
      :rules="[
        { required: true, message: '域名不能为空', trigger: 'blur' },
        { reg:/^--------$/, validator: checkDomain, trigger: 'blur' }
      ]">
      <el-input v-model="item.value" placeholder="请输入内容"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      dynamicValidateForm: {
        domains: [
          { value: ''},
          { value: ''},
          { value: ''},
        ]
      }
    };
  },
  methods: {
    checkDomain(rule, value, callback){
      //自定义校验规则
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
        }
      });
    }
  }
}
</script>

2. 综合应用

案例中, Element-ui 表单里嵌套了表格,表格内每个单元格都能进行表单控件的输入、选择、上传文件等操作,同时能针对整个表单的规则进行校验。

在这里插入图片描述

<template>
  <div>
    <el-button type="primary" size="mini" @click="saveTableForm('tableForm')">保存</el-button>
    <el-form
      :model="tableForm"
      ref="tableForm">
      <el-table
        :data="tableForm.tableData"
        border
        stripe>
        <el-table-column label="省份" prop="province"></el-table-column>
        <el-table-column label="城市">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.city'"
              :rules="tableDataRules.city">
              <el-select size="mini" v-model="scope.row.city" placeholder="请选择" clearable>
                <el-option
                  v-for="item in scope.row.cityOPtions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作人">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.name'"
              :rules="tableDataRules.name">
              <el-input v-model="scope.row.name" placeholder="操作人" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="文件">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.file'"
              :rules="tableDataRules.file">
              <!-- 在组件的回调函数里加一个索引的参数 -->
              <el-upload
                multiple
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-progress="function(event,file,fileList){
                  return handleUploadProgress(event,file,fileList)}"
                :on-remove="function(file,fileList){
                  return handleUploadRemove(file,fileList,scope.$index)}"
                :on-success="function(res,file,fileList){
                  return handleUploadSuccess(res,file,fileList,scope.$index)}"
                :file-list="uploadFileList[scope.$index]">
                <el-button type="text">上传文件</el-button>
              </el-upload>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableForm: {
        tableData: [
          {
            province: "湖北",
            city: "",
            cityOPtions:[
              {label: '武汉市',value:'武汉市'},
              {label: '宜昌市',value:'宜昌市'}
            ],
            name: "",
            file:'',
          },{
            province: "重庆",
            city: "",
            cityOPtions:[
              {label: '渝北区',value:'渝北区'},
              {label: '九龙坡区',value:'九龙坡区'}
            ],
            name: "",
            file:'',
          },
        ],
      },
      tableDataRules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        city: [
          { required: true, message: "请选择城市", trigger: "change" },
        ],        
        file: [
          { required: true, message: "请上传文件", trigger: "change" },
        ],
      },
      uploadFileList:[[]], // 上传文件列表
    };
    
  },
  methods: {
    // 保存
    saveTableForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('校验通过',this.tableForm,this.uploadFileList)
        }
      });
    }, 
    // 预览图片
    handleUploadProgress(event,file,fileList) {},
    // 删除图片
    handleUploadRemove(file, fileList, index) {
      this.tableForm.tableData[index].file = '';
      this.uploadFileList[index] = fileList;
    },
    // 文件上传
    handleUploadSuccess(res, file, fileList, index) {
      this.tableForm.tableData[index].file = res.id;
      // 上传之后,把返回的fileList赋值给对应组件的fileList
      this.uploadFileList[index] = fileList;
    }
  },
};
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/141331.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!