vue 表格内嵌套填写表格 (嵌套表格的增删改查逻辑)

  • Post author:
  • Post category:vue


效果图:

点击新增后跳转到新增页面

新增:

// 新增 / 修改
    addOrUpdateHandle (id) {
      this.$router.push({
        name: 'backUseinfo',
        params: {
          id: id,
          disable: false
        }
      })
      // this.addOrUpdateVisible = true
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.init(id)
      // })
    },

这里是在router中新增了路由

一点击新增就路由跳转到了一个新的页面

效果图如下,点击保存之后,要把这张表里所有的信息都弄到跳转之前的那个表里去。

上部分是需要填写的表单

下部分是一个表格需要填写

表单部分

 <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="80px"
        :inline="true"
      >
        <div style="margin-bottom: 20px">
          <!--         <el-button
            type="white"
            @click="
              $router.push({
                name: 'pesticide-useinfo',
              })
            "
            >返回</el-button
          >

                     <el-button
            v-if="!disabled"
            type="primary"
            @click="dataFormSubmit()"
            >保存</el-button
          > -->
          <el-button
            @click="addOneLine()"
            style="right: 75px; position: absolute; margin-top: 20px"
            type="primary"
            :disabled="isnewone"
            >新增记录</el-button
          >
          <el-button
            @click="deleteHandle()"
            style="right: 200px; position: absolute; margin-top: 20px"
            type="danger"
            :disabled="dataListSelections.length <= 0"
            >批量删除</el-button
          >
          <!--            <el-button
          v-if="!disabled"
          type="primary"
          @click="dataFormSubmit()"
          >新增</el-button
        > -->
        </div>
        <div>
          <el-form-item label="户主编号" prop="farmerId">
            <!-- <el-input
              v-model="dataForm.farmerId"
              :disabled="disabled"
              placeholder="户主编号"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"
              :maxlength="15"
            ></el-input> -->
            <el-tooltip
              class="item"
              effect="dark"
              content="请先填写农户信息表的户主编号"
              placement="top"
            >
              <el-button style="width: 150px; height: 36px"> </el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="年份" prop="dateyear">
            <!-- <el-input
            v-model="dataForm.dateyear"
            :disabled="disabled"
            placeholder="年份"
          ></el-input> -->
            <el-date-picker
              type="year"
              placeholder="选择年份"
              v-model="dataForm.dateyear"
              style="width: 100%"
              format="yyyy"
              value-format="yyyy"
              :disabled="true"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="任务id" prop="taskId">
            <el-input
              onkeyup="this.value = this.value.replace(/[\u4E00-\u9FA5]/g,'');"
              v-model="dataForm.taskId"
              :disabled="disabled"
              placeholder="任务id"
              :maxlength="15"
            ></el-input>
          </el-form-item> -->
        </div>
      </el-form>

表格部分(我简写了,这个表分为两部分,一部分是购买记录表,一部分是使用去向表)

如何在表格里合并单元格呢,在<el-table-column>里嵌套<el-table-column>即可

<el-table
        :data="dataForm.details"
        @selection-change="selectionChangeHandle"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          prop="id"
          align="center"
          label="农药购买记录"
          width="150"
        >
          <el-table-column align="center" type="index" width="50">
          </el-table-column>
          <el-table-column
            prop="purchaseDate"
            align="center"
            label="日期"
            width="140"
          >
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.purchaseDate"
                type="date"
                placeholder="日期"
                :disabled="disabled"
                style="width: 100%"
                format="MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </template>
          </el-table-column>
         </el-table-column>
        <el-table-column
          prop="name"
          align="center"
          label="农药使用去向记录"
          width="180"
        >
          <el-table-column
            prop="medicationDate"
            align="center"
            label="用药日期"
            width="180"
          >
            <template slot-scope="scope">
               <el-date-picker
                v-model="scope.row.medicationDate"
                type="date"
                placeholder="播种日期"
                :disabled="disabled"
                style="width: 100%"
                format="MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </template>
          </el-table-column>       
        </el-table-column>
      </el-table>

data声明部分

 data () {
    return {
      isnewone: false,
      disabled: false,
      visible: false,
      dataForm: {
        id: 0,
        farmerId: '',
        dateyear: '',
        taskId: ''
      },
      detail: {
        id: '',
        purchaseDate: '',
        pdNo: '',
        commonName: '',
        purchaseAmount: '',
        purchaseCost: '',
        packagings: '',
        packingSpecification: '',
        medicationDate: '',
        cropId: '',
        controlObject: '',
        medicationArea: '',
        totalDosage: '',
      },
    }
  },

然后我们来看新增记录addOneLine方法

一开始底部的数据其实应该是无数据的,点击新增,会有一条数据

 addOneLine () {
      let data = this.dataForm
      // data.details.push(JSON.parse(JSON.stringify(this.detail)))
      let details = this.dataForm.details
          data.details.push(JSON.parse(JSON.stringify(this.detail)))
       },

但是这里需要设定的是只要一进入这个页面,就需要看到一行新增待填数据

所以这里写一个init方法

 init (id, disabled) {
      this.disabled = disabled
      this.dataForm.id = id || ''
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        //判断是修改还是新增
        if (this.dataForm.id) {
          this.$http({
            url: `/pesticide/useinfo/info/${this.dataForm.id}`,
            method: 'get'
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.useinfo
              // console.log(data.useinfo);
              // console.log(this.dataForm, 5555555555555555);
            }
          })
        } else {
          //如果是新增就 插入一条空数据(dataForm.details [detail])
          //插入一条空数据怎么写呢
          //
          // this.dataForm = this.dataForm.details [this.detail]
          //  <template slot-scope="scope">
          //  {{(scope.row.id)}}
          // </template>
          // debugger
          let data = JSON.parse(JSON.stringify(this.dataForm))
          let details = []
          details.push(JSON.parse(JSON.stringify(this.detail)))
          details = details.map(item => {
            // 由于农药中文输入框的value改成整条数据,所以初始化时commonName也应该是一个对象
            return { ...item, commonName: { commonName: item.commonName, pdNo: item.pdNo } }
          })

          data.details = details

          this.dataForm = data
          // this.dataForm.details = []
          // this.dataForm.details.push(JSON.parse(JSON.stringify(this.detail)))
          // console.log(this.dataForm);
        }
      })
    },

然后点击填写数据点击保存

 // 表单提交
    dataFormSubmit () {     
      this.$refs['dataForm']
        .validate((valid) => {
          console.log(valid, 1111111111111111111);
          if (valid) {
            let details = this.dataForm.details
              this.$http({
              url: `/pesticide/useinfo/${!this.dataForm.id ? 'save' : 'update'}`,
              method: 'post',
              data: this.dataForm
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          }
        })
    },

批量删除功能

 //删除
    deleteHandle () {
      // if (rows) {
      //   rows.forEach((row) => {
      //     this.$refs.multipleTable.toggleRowSelection(row);
      //   });
      // } else {
      //   this.$refs.multipleTable.clearSelection();
      // }
      //首先获取到对象(要删除的对象)
      //在获取到整个table里面的数据
      //判断是否相等 是的话就删除

      let finalData = JSON.parse(JSON.stringify(this.dataForm.details));
      let delIds = [];
      this.dataListSelections.forEach((item) => {
        this.dataForm.details.forEach((tableDataItem, i) => {
          // console.log(item == tableDataItem);
          if (item == tableDataItem) {
            // delete finalData[i];
            delIds.push(i);
          }
        });
      });
      function sortNumber (a, b) {
        //升序
        return a - b;
      }
      delIds.sort(sortNumber);
      let delNum = 0;
      for (let i = 0; i < delIds.length; i++) {
        finalData.splice(delIds[i] - delNum, 1);
        delNum++;

      }

      // delIds.forEach((item) => {

      // i = i - 1;
      // });
      this.dataForm.details = finalData;
    },

删除单行:

                <el-table-column
                fixed="right"
                header-align="center"
                align="center"
                width="150"
                label="操作"
              >
                <template slot-scope="scope">
                  <button @click="addXiaoGou(scope.row)" :disabled="disabled">
                    添加
                  </button>
                  <button
                    @click="deleteItem(scope.$index, scope.row)"
                    :disabled="disabled"
                    type="danger"
                  >
                    删除
                  </button>
                 </template>
              </el-table-column>

//单独删除
    deleteItem (index, row) {
      console.log(index);
      this.$confirm('确定对所选项进行[删除]操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.dataForm.details.splice(index, 1)

        // this.dataForm.details.splice(index, 1)
      })
    },

使用到的是js中的splice()方法

语法:

arr.splice(index,1),

arr是数组



版权声明:本文为weixin_49393290原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。