el-form动态增减表单项,多层嵌套

先上效果图

代码图

<template>
  <div>
    <el-form :model="form.third" ref="form" :rules="rules" label-width="80px">
      <div v-for="(item, index) in details" :key="index">
        <template v-if="index == 0">
          <el-form-item label=""  :prop="'details.' + index + '.minNum'"
            :rules="{ required: true, message: 'minNum不能为空', trigger: 'blur' }">
            <el-input v-model="item.name1"></el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label=""  :prop="'details.' + index + '.num'"
            :rules="{ required: true, message: 'num不能为空', trigger: 'blur' }">
            <el-input v-model="item.name2"></el-input>
          </el-form-item>
        </template>
      </div>
      <el-form-item>
        <el-button type="primary" size="default" @click="getData">获取数据</el-button>

        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      form: {
        third: {
          details: []
        }
      },
      rules: {}
    };
  },
  computed: {
    details() {
      return this.form.third.details
    },
  },
  methods: {
    async getData() {
      const res = await fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json()).then(json => { return json })
      console.log(res);
      this.form.third.details = res.slice(0, 3).map((item, index) => {
        if (index == 0) {
          return {
            minNum: null
          }
        } else {
          return {
            num: null,
          } 
        }
      })
      // 再次校验 arr 中所有的 name
      this.$nextTick(() => {
        this.form.third.details.forEach((_, index) => {
          if(index == 0) {
            this.$refs.form.validateField('details.' + index + '.minNum');
          } else {
            this.$refs.form.validateField('details.' + index + '.num');
          }
        });
      })
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(valid);
        } else {
          console.log(valid);
          return false;
        }
      });
    }
  },
  async created() {
  },
  mounted() {

  },
  
};

</script>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值