ElmentUI表单校验自定义——动态添加和删除

需求:

1.表单列表:点击按钮增加一行、删除、校验输入;

2.表格列表:点击按钮增加一行、删除、输入校验。

<template>
  <el-form :model="form" ref="ruleForm" label-width="100px">
    <el-form-item label="负责人" prop="principal" :rules="rules.principal">
      <el-input v-model="form.principal"></el-input>
    </el-form-item>
    <el-form-item label="活动列表">
      <el-row v-for="(item, index) in form.activities" :key="index" style="margin-bottom: 20px;">
        <el-col :span="11">
          <el-form-item :label="`名称${index + 1}`" :prop="`activities.${index}.name`" :rules="rules.name">
            <el-input v-model="item.name" placeholder="请输入活动名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item :label="`主题${index + 1}`" :prop="`activities.${index}.content`" :rules="rules.content">
            <el-input v-model="item.content" placeholder="请输入活动主题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2" style="text-align:center; font-size: 16px" >
          <i class="el-icon-circle-plus-outline" @click="addItem" v-if="index === 0"></i>
          <i class="el-icon-remove-outline" @click="removeItem(index)" v-else></i>
        </el-col>
      </el-row>
    </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>
export default {
  data () {
    return {
      form: {
        principal: '',
        activities: [{
          name: '',
          content: ''
        }]
      },
      rules: {
        principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入活动主题', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return console.log('未通过校验')
      })
    },
    addItem () {
      this.form.activities.push({
        name: '',
        content: ''
      })
    },
    removeItem (index) {
      this.form.activities.splice(index, 1)
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<template>
  <el-form :model="form" ref="ruleForm" label-width="0px" style="margin: 20px;">
    <el-form-item>
      <el-button type="primary" @click="addItem('ruleForm')">新增一行</el-button>
      <el-button type="primary" @click="saveItem('ruleForm')" :disabled="!isAdd">保存</el-button>
      <el-button type="primary" @click="resetForm('ruleForm')" :disabled="!isAdd">重置</el-button>
    </el-form-item>
    <el-form-item>
      <el-table border :data="form.tableData">
        <el-table-column
          v-for="(item, index) in form.tableColumn"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          align="center"
        >
          <template slot-scope="scope">
            <el-form-item :prop="`tableData.${scope.$index}.${item.prop}`" :rules="rules[item.prop]" v-if="isSave">
              <el-input v-model="scope.row[item.prop]" :placeholder="`请输入${item.label}`"></el-input>
            </el-form-item>
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>
        <el-table-column width="80" align="center" label="操作" v-if="isSave">
          <template slot-scope="scope">
            <el-button round plain type="danger" @click="removeItem(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      isAdd:false,
      isSave:false,
      form: {
        tableColumn: [
        {
          default: "",
          label: "输出",
          prop: "output"
        },
        {
          default: "",
          label: "比例",
          prop: "proportion"
        }],
        tableData: []
      },
    }
  },
  computed: {
    proportionSum(){
      let res = this.form.tableData.reduce((acc,cur) => {// 上次累计值+正在处理取值+索引+源数组
          return acc+Number(cur.proportion)
      },0)
      return res
    },
    rules() {
      const rules = {};
      this.form.tableColumn.forEach((item) => {
        rules[item.prop] = [{ required: true, message: item.label+"不可为空", trigger: "blur" }]
        if(item.prop==='proportion'){
          const validatorP = (rule, value, callback) => {
            if (value) {
              const rtx = /^-?(0\.\d*[1-9]+\d*)|1/
              if (!value.match(rtx)) {
                callback(new Error('须是大于0,小于或等于1的数字'))
              } else {
                callback()
              }
            } else {
              callback(new Error('比例不可为空'))
            }
          }
          rules[item.prop].push(            
          {
            // pattern: /^-?(0\.\d*[1-9]+\d*)|1/,
            // message: "须是大于0,小于或等于1的数字",
            validator: validatorP, 
            trigger: "blur"
          })
        }
      });
      return rules;
    }
  },
  methods: {
    saveItem(formName){
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return
        } else {
          let res = this.form.tableData.reduce((acc,cur,index,arr) => {// 上次累计值+正在处理取值+索引+源数组
              return acc+Number(cur.proportion)
          },0)
          if(res!==1){
            this.$message.error('所有列表比例之和必须等于1')
            this.isSave = true
            this.isAdd = true
          }else{
            this.isSave = false
            this.isAdd = false
          }
        }
      })
    },
    addItem(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return
        } else {
          this.form.tableData.push({
            output: '',
            proportion: ''
          })
          this.isSave = true
          this.isAdd = true
        }
      })
    },
    removeItem(scope) {
      this.form.tableData.splice(scope.$index, 1);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.form.tableData = []
      this.isSave = false
      this.isAdd = false
    }
  }
}
</script>

-end-

posted @ 2020-09-21 15:46  桥南小院  阅读(700)  评论(0编辑  收藏  举报