vue + element:table 结合 form 实现动态新增、编辑表格,并且校验

根据场景不一样,可以区分为整体校验和逐条校验;

一、整体校验

<template>
  <div>
    <el-button type="success" @click="handleAdd()">add</el-button>
    <el-button type="success" @click="submit()">submit</el-button>
    <el-form :model="ruleForm" ref="ruleForm" :key="flash">
      <el-table :data="ruleForm.tableData" style="width: 100%">
        <el-table-column
          v-for="(item, index) in ruleForm.tableHeader"
          :prop="item.keys"
          :label="item.label"
          :key="index">
          <template slot-scope="scope">
            <span v-if="scope.row.isSet">
              <el-form-item
                :prop="'tableData.' + scope.$index + '.' + item.keys"
                :rules="{
                  validator: validateFn,
                  trigger: 'blur',}">
                <el-input v-model="scope.row[item.keys]"></el-input>
              </el-form-item>
            </span>
            <span v-else>
              {{ scope.row[item.keys] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isSet" type="primary" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flash:0,
      ruleForm: {
        tableHeader: [
          {
            label: "日期",
            keys: "date",
          },
          {
            label: "姓名",
            keys: "name",
          },
          {
            label: "地址",
            keys: "address",
          },
        ],
        tableData: [
          {
            date: "2016-05-02",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1518 弄",
          }
        ],
      },
    };
  },
  methods: {
  	//自定义校验规则
  	validateFn(rule, value, callback){
  		let arr = rule.field.split('.')[2]
  		if(arr == 'date'){
  			callback(new Error("请输入日期"));
  		}else if(arr == 'name'){
  			callback(new Error("请输入名称"));
  		}else if(arr == 'address'){
  			callback(new Error("请输入地址"));
  		}else{
  			callback()
  		}
  	},
  	//提交
    submit(){
		this.$refs.ruleForm.validate(valid=>{
			if(valid){
				this.ruleForm.tableData.forEach((item, index) => {
			        item.isSet = false;
			    });
				this.$set(this.ruleForm.tableData);
				this.flash++
			}else{
				return false
			}
		})
    },
    //新增
    handleAdd() {
      let row = {};
      this.ruleForm.tableHeader.forEach((item, index) => {
        row.isSet = true;
      });
      this.ruleForm.tableData.push(row);
    },
    //编辑
    handleEdit(index, row) {
      row.isSet = true;
      this.$set(this.ruleForm.tableData, index, row);
    },
    //删除
    handleDelete(index, row) {
      this.ruleForm.tableData.splice(index, 1);
    },
  },
};
</script>

这里是使用 form 包裹 table ,注意动态绑定 prop 的拼接规则,这样可以通过最外层的对象 ruleForm 来统一对输入框进行校验;

效果图如下:
vue + element:table 结合 form 实现动态新增、编辑表格,并且校验_第1张图片

二、逐条校验

<template>
  <div class="formData">
    <el-table :data="list" style="width: 100%">
      <el-table-column prop="key" label="KEY" min-width="180">
        <template slot-scope="{ row }">
          <div v-if="!row.isModified">
            {{ row.key }}
          </div>
          <el-form
            v-else
            :ref="'keyForm' + row.id"
            label-width="0px"
            :class="row.isValid ? 'demo-ruleForm' : ''"
            :model="row">
            <el-form-item
              prop="key"
              :rules="[
                {
                  validator: validateKey,
                  trigger: ['blur', 'change'],
                  id: row.id,
                },
              ]">
              <el-input v-model="row.key" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="value" label="VALUE" min-width="180">
        <template slot-scope="{ row }">
          <div v-if="!row.isModified">
            {{ row.value }}
          </div>
          <el-form
            :ref="'valueForm' + row.id"
            label-width="0px"
            :class="row.isValid ? 'demo-ruleForm' : ''"
            v-else
            :model="row">
            <el-form-item
              prop="value"
              :rules="[
                {
                  validator: validateValue,
                  trigger: ['blur', 'change'],
                  id: row.id,
                },
              ]">
              <el-input v-model="row.value" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="{ row }">
          <el-button v-if="!row.isModified" type="text" size="small" @click="editKey(row.id)">编辑</el-button>
          <el-button v-else type="text" size="small" @click="confirm(row.id)">确认</el-button>
          <el-button type="text" size="small" @click="deleteKey(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="addKey">add</el-button>
  </div>
</template>
<script>
export default {
  name: "formData",
  data() {
    return {
      list: [
        {
          key: "vue",
          value: "2.21",
          isModified: false,
          isValid: false,
          id: 0,
        }
      ],
    };
  },
  computed: {
   //过滤出已经存在的key
    existKeys() {
      return this.list
        .filter((item) => !item.isModified)
        .map((item) => item.key);
    },
    //过滤出已经存在的value
    existValues() {
      return this.list
        .filter((item) => !item.isModified)
        .map((item) => item.value);
    },
  },
  methods: {
    //删除
    deleteKey(index) {
    	let ind = this.findItem(index)
        this.list.splice(ind, 1);
    },
    //编辑
    editKey(index) {
    	let ind = this.findItem(index)
      	this.list[ind].isModified = true;
    },
    //新增
    addKey() {
      this.list.push({
        key: "",
        value: "",
        isModified: true, //切换编辑状态的标志位
        isValid: false, //判断Key的校验结果
        id: this.list.length,
      });
    },
    promiseValidate(key) {
      return new Promise((resolve, reject) => {
        try {
          this.$refs[key].validate((valid) => {
            resolve(valid);
          });
        } catch (err) {
          reject(err);
        }
      });
    },
    //确认
    async confirm(index) {
      const validates = await Promise.all([
        this.promiseValidate("keyForm" + index),
        this.promiseValidate("valueForm" + index),
      ]);
      if (validates.every((item) => item)) {
        this.list[index].isModified = false;
      }
    },
    //查找需要当前校验的项
    findItem(id){
    	for(let i in this.list){
    		if(this.list[i].id == id){
    			return i
    		}
    	}
    },
    validateKey(rule, value, callback) {
    	let ind = this.findItem(rule.id)
    	console.log(ind)
      if (value === "") {
        this.list[ind].isValid = true
        callback(new Error("请输入Key"));
      } else if (this.existKeys.includes(value)) {
        this.list[ind].isValid = true
        callback(new Error("Key的值已经重复"));
      } else {
        callback();
      }
    },
    validateValue(rule, value, callback) {
    	let ind = this.findItem(rule.id)
      if (value === "") {
        this.list[ind].isValid = true
        callback(new Error("请输入Value"));
      } else if (this.existValues.includes(value)) {
        this.list[ind].isValid = true
        callback(new Error("value的值已经重复"));
      } else {
        callback();
      }
    },
  },
};
</script>
<style>
.formData {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 0;
}
.demo-ruleForm {
  margin: 20px 0;
}
</style>

这种是每一行分别校验,主要是将 form 嵌套在 table 里面;这个案例实现了所有 key 和 所有 value 去重的校验;

效果图如下:
vue + element:table 结合 form 实现动态新增、编辑表格,并且校验_第2张图片

你可能感兴趣的:(vue,elementUI,vue.js,前端,javascript)