element表单中一个el-form-item下多个form-item项校验(循环校验)

在vue+element的项目中,需要对form表单下的一个form item中校验多项数据,如下图:
element表单中一个el-form-item下多个form-item项校验(循环校验)_第1张图片
代码实现(需要注意prop的值):

<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>

你可能感兴趣的:(Vue,vue,element,ui)