前端对element table合并相同项

<template>
  <div>
    <!-- 按钮 -->
    <div style="position: relative; margin-left: 4px; margin-top: 4px; margin-bottom: -4px">
      <nav-permission-button :buttonData="topButton" :comp="comp"></nav-permission-button>
      <!-- <el-button @click="handleAdd">新增</el-button>
      <el-button @click="handleEdit">编辑</el-button>
      <el-button @click="handleDel">删除</el-button> -->
      <!-- <el-button type="warning" class="back-btn" @click="goBackToManagement">返回</el-button> -->
    </div>
     <!-- 列表 -->
    <common-wrapper>
      <common-table :flex="180">
        <template slot="table">
          <el-table
            ref="tableRef"
            height="100%"
            stripe
            border
            size="mini"
            highlight-current-row
            v-loading="isListLoading"
            :data="tableData"
            :span-method="objectSpanMethod"
            @selection-change="(selected) => (selectRow = selected)"
           >
              <el-table-column type="selection" width="50" ></el-table-column>
              <el-table-column type="index" align="center" label="序号" min-width="50"></el-table-column>
              <el-table-column prop="valuationNumber" label="策略编号" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="valuationName" label="策略名称" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="valuationTag" label="时段标识" align="center" show-overflow-tooltip :formatter="formatValuationTag"></el-table-column>
              <el-table-column prop="month" label="适用月份" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="effectStartTime" label="开始时间" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="effectEndTime" label="结束时间" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="elecPrice" label="电费" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="servicePrice" label="服务费" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" prop="mergeSameMonth" width="240" align="center">
                <template slot-scope="scope">
                  <el-button
                          v-for="(btn, index) in rowButton"
                          :key="index"
                          type="primary"
                          @click="buttonFun(btn, scope.row)"
                       >
                          {{btn.name}}
                      </el-button>
                </template>
                <!-- <el-button @click="handleRowEdit">编辑</el-button>
                <el-button @click="handleRowDel">删除</el-button>
                <el-button @click="handleRowDetails">详情</el-button> -->
              </el-table-column>
          </el-table>
        </template>
      </common-table>
    </common-wrapper>
      <!-- 新增、修改 -->
    <Update
      ref="dialogRef"
      :monthOptions="monthOptions"
      :periodtimeType="periodtimeType"
      :row="row"
      @save-success="saveSuccess"
    />
  </div>

</template>

<script>
import getDict from '@/utils/getDict'
import NavPermissionButton from '@/components/navButton/buttons'
import CommonWrapper from '@/components/commonWrapper'
import CommonTable from '@/components/commonTable'
import Update from './components/Update'
import { getBtnArray } from '@/utils/getBtn.js'

export default {
  name: 'Details',
  components: {
    NavPermissionButton,
    CommonWrapper,
    CommonTable,
    Update

  },
  // 层级关系传值
  props: {
    rowInfo: {
      type: Object
    },
    isInSide: {
      type: Boolean
    },
    resourceId: {// 动态获取按钮
      type: String
    }
  },
  data () {
    return {
      comp: this,
      tableData: [],
      buttonData: [],
      isListLoading: false,
      selectRow: [],
      topButton: [],
      rowButton: [],
      searchParams: {
        valuationId: ''
      },
      monthOptions: [],
      row: {},
      // 合并表格
      mergedColumns: ['valuationNumber', 'valuationName', 'month', 'mergeSameMonth'],
      spanMap: {}
    }
  },
  computed: {
    periodtimeType () {
      return getDict('periodtimeType')
    }
  },
  async beforeMount () {
    if (this.isInSide) {
      // 代表二级页面跳转
      let obj = await getBtnArray(this.resourceId)
      this.topButton = obj.topButton
      this.rowButton = obj.rowButton
    } else {
      // 代表路由跳转
      let obj = await getBtnArray(this.comp.$route.meta['resourceId'])
      this.topButton = obj.topButton
      this.rowButton = obj.rowButton
    }
  },
  mounted () {
    this.setMonthOptions()
    if (this.isInSide) {
      this.tableData = []
      this.row = this.rowInfo
      this.searchParams.valuationId = this.row.valuationId
      this.queryList(this.searchParams)
    }
  },
  methods: {
    // 设置月份数组
    setMonthOptions () {
      this.monthOptions = []
      for (let i = 1; i < 13; i++) {
        this.monthOptions.push({ label: `${i}`, value: String(i) })
      }
    },
    // 动态button事件
    buttonFun (btn, row) {
      if (this[btn.click]) {
        this[btn.click](row)
      } else {
        console.log('方法未定义!')
      }
    },
    saveSuccess () {
      this.queryList(this.searchParams)
    },
    // search
    queryList (params) {
      const searchParams = Object.assign(this.searchParams, params)
      this.getTableList(
        {
          ...searchParams
        }
      )
    },
    // 查询列表
    getTableList (params) {
      this.isListLoading = true
      this.$api['pricingRuleDetails.list'](params).then(res => {
        this.tableData = res
        // 处理返回的数据,合并月份相同的数据
        this.getSpanArr(this.tableData)
        this.$nextTick(() => {
          this.$refs.tableRef.doLayout()
        })
        this.isListLoading = false
      })
    },
    getSpanArr (data) {
      data.forEach(item => { // 添加mergeSameMonth字段合并操作列
        item.mergeSameMonth = item.month
      })
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.mergedColumns.forEach(column => {
            this.spanMap[column] = {
              spanArr: [1],
              pos: 0
            }
          })
        } else {
          this.mergedColumns.forEach(column => {
            if (data[i][column] === data[i - 1][column]) {
              this.spanMap[column].spanArr[this.spanMap[column].pos] += 1
              this.spanMap[column].spanArr.push(0)
            } else {
              this.spanMap[column].spanArr.push(1)
              this.spanMap[column].pos = i
            }
          })
        }
      }
    },
    objectSpanMethod ({ column, rowIndex }) {
      if (this.spanMap[column.property]) {
        const _row = this.spanMap[column.property].spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    formatValuationTag (row, column, cellVal) {
      let tag = ''
      this.periodtimeType.map(item => {
        if (cellVal === item.value) {
          tag = item.label
        }
      })
      return tag
    },
    // 新增
    handleAdd () {
      this.$refs.dialogRef.open({})
    },
    // 编辑
    handleEdit () {
      if (this.selectRow.length !== 1) {
        this.$message.warning('请勾选一项进行编辑')
        return false
      }
      const row = this.selectRow[0]
      this.eidt(row)
    },
    // 删除
    handleDel () {
      if (this.selectRow.length === 0) {
        this.$message.warning('请至少勾选一项进行删除')
        return false
      }
      let monthList = []
      this.selectRow.map(item => {
        monthList.push(item.month)
      })
      // 对month去重
      monthList = [...new Set(monthList)]
      // 准备空数组,按照月份去查找所以详情id
      let idsList = []
      monthList.map(month => {
        let sameMonthDataList = this.getSameMonthData(this.tableData, month)
        sameMonthDataList.map(item => {
          idsList.push(item.valuationDetailId)
        })
      })
      let ids = idsList.join(',')
      this.deleteData({ ids })
    },
    // 删除接口
    deleteData (params) {
      this.$confirm('确认删除选中的数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api['pricingRuleDetails.removeByIds'](params).then(res => {
          if (res === true) {
            this.$message.success('删除成功')
            this.queryList(this.searchParams)
          } else {
            this.$message.error('删除失败')
          }
        }).catch(err => {
          const { response } = err
          if (response) {
            const { data } = response
            this.$message.error(data.message || '删除失败')
          } else {
            this.$message.error(err.message)
          }
        })
      }).catch(() => {})
    },
    handleRowEdit (row) {
      this.eidt(row)
    },
    eidt (row, readOnly = false) {
      // 1得到相同月份的数据
      let month = row.month
      let monthList = []
      monthList = month.split('|')
      monthList.forEach((item, index) => {
        if (!item) {
          monthList.splice(index, 1)
        }
      })
      let sameMonthDataList = this.getSameMonthData(this.tableData, month)
      let formData = {
        valuationId: row.valuationId,
        valuationName: row.valuationName,
        monthList: monthList,
        tableData: sameMonthDataList
      }
      this.$refs.dialogRef.open(formData, readOnly)
    },
    getSameMonthData (tableData, month) {
      let sameMonthDataList = []
      tableData.map(item => {
        if (month === item.month) {
          sameMonthDataList.push(item)
        }
      })
      return sameMonthDataList
    },
    handleRowDel (row) {
      let sameMonthDataList = this.getSameMonthData(this.tableData, row.month)
      let detailIdsList = []
      sameMonthDataList.map(item => {
        detailIdsList.push(item.valuationDetailId)
      })
      let ids = detailIdsList.join(',')
      this.deleteData({ ids })
    },
    handleRowDetails (row) {
      this.eidt(row, true)
    }
  }
}
</script>
<style lang="scss" scoped>
  .back-btn {
    position: absolute;
    right: 20px;
  }
</style>

只需要关注objectSpanMethod方法设计的参数即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值