vue2的element的table组件使用form校验

1.需求描述

vue2有时候做自增表格el-table,希望能够带一些校验,但又不想手搓校验逻辑,可以借用el-form的校验逻辑。

2.代码处理

1. html

<template>
    <div class="sad-cont">
      <el-form ref="form" :model="form">
        <el-table :data="form.tableData" border size="mini">
          <el-table-column align="center" prop="other" label="名称" width="230">
            <template slot-scope="scope">
              {{ scope.row.min }} ~ {{ scope.row.max }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="min" label="最小值" width="230">
            <template slot-scope="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.min'" :rules="ruleForm.min">

                <el-input-number v-model="scope.row.min" placeholder="请输入最小值" controls-position="right" />
                <template slot="error" slot-scope="itemScope">
                  <!-- 自定义错误信息 -->
                  <div v-if="itemScope.error">
                    <el-tooltip :content="itemScope.error" placement="top">
                      <i class="el-icon-warning-outline sad-item-error" />
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="max" label="最大值" width="230">
            <template slot-scope="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.max'" :rules="ruleForm.max">
                <el-input-number v-model="scope.row.max" placeholder="请输入最大值" controls-position="right" />
                <template slot="error" slot-scope="itemScope">
                  <!-- 自定义错误信息 -->
                  <div v-if="itemScope.error">
                    <el-tooltip :content="itemScope.error" placement="top">
                      <i class="el-icon-warning-outline sad-item-error" />
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right">
            <template slot="header">
              <div>
                <span>操作</span>
                <el-tooltip content="添加数据" placement="top">
                  <el-button
                    size="mini"
                    icon="el-icon-plus"
                    class="table-icon-style sad-btn2"
                    @click="addRow()"
                  />
                </el-tooltip>

              </div>
            </template>
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="success"
                class="table-icon-style"
                @click="deleteRow(scope.row, scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    

    <div>
      <el-button type="primary" @click="submitData">确 定</el-button>
    </div>
  </div>
</template>

2. js

import { notEmpty, isEmpty } from '@/utils/validate';

export default {
  components: {
  },
  props: {
    //  默认数据
    defaultData: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      form: {
        tableData: []
      },
      rules: {},
      ruleForm: {
        min: [
          { required: true, message: '请输入最小值', trigger: 'blur' },
          { validator: (rule, value, callback) => this.validateValue(rule, value, callback, 'min'), trigger: 'blur' }
        ],
        max: [
          { required: true, message: '请输入最大值', trigger: 'blur' },
          { validator: (rule, value, callback) => this.validateValue(rule, value, callback, 'max'), trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.initData();
  },
  methods: {
    notEmpty, isEmpty,

    //  初始化
    initData() {
      const { defaultData, form: { tableData }} = this;
      tableData.push(...defaultData.map(item => {
        return {
          max: item.max,
          min: item.min
        };
      }));
    },

    //  校验数据
    validateValue(rule, value, callback, key) {
      const { form: { tableData }} = this;
      const { field } = rule;
      const fieldKeys = field.split('.');
      const index = fieldKeys[1];
      const data = tableData[index];
      const maxValue = 999999999;
      const minValue = maxValue * -1;

      if (notEmpty(data.max) && notEmpty(data.min)) {
        if (data.max < data.min) {
          const text1 = key === 'max' ? '最大值' : '最小值';
          const text2 = key === 'max' ? '最小值' : '最大值';
          const text3 = key === 'max' ? '小于' : '大于';
          callback(new Error(`${text1}不得${text3}${text2}!`));

          return;
        }
      } else {
        if (key === 'max') {
          if (value * 1 > maxValue) {
            callback(new Error(`最大值不得大于${maxValue}!`));
            return;
          } else { /**/ }
        } else if (key === 'min') {
          if (value * 1 < maxValue) {
            callback(new Error(`最小值不得小于${minValue}!`));
            return;
          } else { /**/ }
        } else { /**/ }
      }

      callback();
    },

    //  导出数据表
    deleteRow(row, index) {
      const { form: { tableData }} = this;
      tableData.splice(index, 1);
    },

    // 添加一行记录
    addRow() {
      const { form } = this;
      form.tableData.push({
        min: 0,
        max: 10
      });
    },

    //  关闭表单
    closeForm() {
      this.$emit('closeForm');
    },

    //  子组件触发form事件
    submitData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { form: { tableData }} = this;
          const obj = {};
          const returnData = [];
          tableData.forEach(item => {
            const { max, min } = item;
            const text = `${min}~${max}`;
            if (!obj[text]) {
              const each = {
                name: text,
                min: min,
                max: max
              };
              obj[text] = each;
              returnData.push(each);
            } else { /**/ }
          });

          this.$emit('submitForm', returnData);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};

3.样式优化

提示样式必须处理,这样才能在表格内显示正常!!!

.el-form-item{
  margin-bottom: 0;
}
.sad-item-error{
  position: absolute;
  color: #F56C6C;
  top: 0;
  left: 100%;
  line-height: 32px;
}
.sad-cont{
  min-height: 200px;
}
.sad-btn2{
  padding: 2px 5px;
}

3. 效果如下

在这里插入图片描述

相关推荐

  1. 使用vueelement上传excel文件

    2024-06-06 07:00:02       16 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-06 07:00:02       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-06 07:00:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-06 07:00:02       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-06 07:00:02       20 阅读

热门阅读

  1. 音视频开发_SDL彻底理解纹理

    2024-06-06 07:00:02       7 阅读
  2. salesforce inactive的用户会收到通知邮件吗

    2024-06-06 07:00:02       8 阅读
  3. Kubernetes (K8s) 普及指南

    2024-06-06 07:00:02       6 阅读
  4. WEB三大主流框架之React

    2024-06-06 07:00:02       7 阅读
  5. Nuxt - middleware 路由中间件

    2024-06-06 07:00:02       7 阅读
  6. 007 异步同步

    2024-06-06 07:00:02       6 阅读
  7. DNS域名

    DNS域名

    2024-06-06 07:00:02      8 阅读
  8. oracle 核心进程

    2024-06-06 07:00:02       6 阅读