Vue+Element+JS動態生成form表單實現新增和刪除操作

ChuaWi98發表於2021-01-05

效果圖:

核心程式碼:

<!-- 新增或修改使用者對話方塊 -->
<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);
    },
}

相關文章