Vue+Element+JS动态生成form表单实现新增和删除操作

效果图:

核心代码:


<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
  <el-form ref="form" :model="form" :rules="rules" label-width="120px">
  	
    <el-row>
      <el-col :span="12">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号" />
        el-form-item>
      el-col>
      <el-col :span="11">
        <el-form-item label="姓名" prop="roomUrl">
          <el-input v-model="form.studentName" placeholder="请输入姓名" />
        el-form-item>
      el-col>
      <el-button
        size="medium"
        type="text"
        icon="el-icon-circle-plus"
        @click="addItem"
      />
    el-row>
    
    <el-row v-for="(item, index) in studentList" :key="index">
      <el-col :span="12">
        <el-form-item
          label="学号"
          :prop="'studentList.' + index + '.studentId'"
        >
          <el-input v-model="item.studentId" placeholder="请输入学号" />
        el-form-item>
      el-col>
      <el-col :span="11">
        <el-form-item
          label="姓名"
          :prop="'studentList.' + index + '.studentName'"
        >
          <el-input v-model="item.studentName" placeholder="请输入姓名" />
        el-form-item>
      el-col>
      <el-button
        size="medium"
        type="text"
        icon="el-icon-delete"
        @click="delItem(index)"
      />
    el-row>
  el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitForm">确 定el-button>
    <el-button @click="cancel">取 消el-button>
  div>
el-dialog>
export default {
  name: "Student",
  data() {
    return {
      // 表单参数
      form: {
        studentList: [],
      },
      // 学生列表信息
      studentList: [
        {
          studentId: "",
          studentName: "",
        },
      ],
      // 表单校验
      rules: {},
    };
  },
}
methods:{
    /** 动态添加&删除学号和姓名 */
    addItem() {
      if (this.form.studentId == null || this.form.studentName == null) {
        this.$confirm("请填写学号或姓名", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
      } else {
        this.studentList.push({
          studentId: "",
          studentName: "",
        });
      }
    },
    delItem(index) {
      this.studentList.splice(index, 1);
    },
}

你可能感兴趣的:(vue,vue,javascript)