element-ui动态增减表单项

先来效果图
在这里插入图片描述
需求:每加一个场次新增一场活动,并添加验证规则

关键代码部分:

          <el-form-item label="活动场次" prop="roundTimeList">
            <el-button type="primary" icon="el-icon-plus" @click="addSession">添加活动场次</el-button>
          </el-form-item>
          <div v-for="(item,index) in formParams.roundTimeList" :key="index">
            <el-form-item
              :label="`活动场次${index+1}`"
              :prop="`roundTimeList[${index}].timeRange`" 
              :prop="'roundTimeList.' + index + '.timeRange'"   `<————关键代码,两种写法都可以,下面有介绍`
              :rules="formRules.roundTimeList0"
            >
              <el-time-picker
                is-range
                v-model="item.timeRange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                value-format="HH:mm:ss"
                style="margin-right:10px"
                :clearable="true"
              ></el-time-picker>
              <el-button type="danger" icon="el-icon-minus" circle @click="delSession(index)"></el-button>
            </el-form-item>
          </div>
      formParams: {
    
    
        roundTimeList: [],
      },
      formRules: {
    
    
        roundTimeList: [
          {
    
     required: true, message: "请添加场次", trigger: "blur" }
        ],
        roundTimeList0: [
          {
    
     required: true, message: "请选择场次时间", trigger: "change" }
        ]
      }
      methods:{
    
    
	    addSession() {
    
    
	      let obj = {
    
    
	        id: null,
	        startTime: "",
	        endTime: "",
	        timeRange: ["00:00:00", "23:59:59"]
	      };
	      if (this.formParams.roundTimeList.length < 10) {
    
    
	        this.formParams.roundTimeList.push(obj);
	      } else {
    
    
	        this.$message.warning(`最多添加${
      
      this.roundTimeList.length}场`);
	      }
	    },  
		delSession(index) {
    
    
	      this.formParams.roundTimeList.splice(index, 1);
	    },
	 }

element ui表单校验prop的链式写法----源码分析

注意: 使用el-time-picker,时间范围选择时,绑定的初始值timeRange不能给空数组[], 给空数组的话会无法选中时间的bug

猜你喜欢

转载自blog.csdn.net/qq_42816550/article/details/106801427
今日推荐