antd table 动态设置 title项 和 属性

837 阅读2分钟
<template>
  <div class="table-list-wrapper">
    <!-- 查询区域 -->
    <div class="ml-3">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-form-item label="客户代码">
            <p-input v-model="queryParam.clientCode" placeholder="请输入客户代码" />
          </p-form-item>
          <p-form-item label="机型">
            <p-input v-model="queryParam.series" placeholder="请输入机型" />
          </p-form-item>
          <p-form-item label="产品ID">
            <p-input v-model="queryParam.productId" placeholder="请输入产品ID" />
          </p-form-item>
          <p-form-item>
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <p-button type="primary" size="small" @click="searchQuery" >查询</p-button>
              <p-button class="ml-2" size="small" ghost type="primary" @click="searchReset" >重置</p-button>
            </span>
          </p-form-item>
        </p-row>
      </p-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator mb-2" style="border-top: 5px">
      <div> <p-icon type="question-circle" /> 线体优先级:A > B > C > D</div>
      <div>
        <p-button class="mr-2" type="primary" size="small" @click="handleAdd"><span class="iconfont icon-xinzeng"></span>新增</p-button>
        <p-button class="mr-2" type="primary" size="small" :loading="exportLoading" @click="handleExportXls(description)"><span class="iconfont icon-daochu"></span>导出 </p-button>
        <p-upload name="file" class="mr-2" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="url.importExcelUrl" @change="handleImportExcel">
          <p-button type="primary" size="small" :loading="importLoading"><span class="iconfont icon-daoru"></span>导入</p-button>
        </p-upload>
        <p-button class="mr-2" type="dashed" size="small" icon="download" @click="handleDownTemplate()"> 下载模板 </p-button>
      </div>
    </div>
    <!-- table区域-begin -->
    <div>
      <p-table
        ref="table"
        rowKey="id"
        size="middle"
        :rowClassName="getRowClassName"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
        :scroll="{ x: scrollX, y: scrollY-42 }"
      >
        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <p-divider type="vertical" />
          <p-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.productId)">
            <a>删除</a>
          </p-popconfirm>
        </template>
        <template v-for="item in extRender"  :slot="item" slot-scope="text,record">
          <p-button type="link" @click="updateType(text,record.productId,item)" >
            <span v-if="text !=undefined && text !=null && text !=''">
              <p-tag :color="text == 'A' ? 'pink' : text == 'B' ? 'green' : ''">
                {{text}}
              </p-tag>
            </span>
            <span v-else style="width:40px;height: 100%;"></span>
          </p-button>
        </template>
      </p-table>
    </div>
    <line-certification-modal ref="modalForm" @ok="handleOk"></line-certification-modal>
    <edit-value-modal ref="editModalForm" @ok="handleOk"></edit-value-modal>
  </div>
</template>

<script>
import { TableMixin } from '@/mixins/TableMixin'
import lineCertificationModal from './modules/lineCertificationModal.vue'
import editValueModal from './modules/editValueModal.vue'
import { listAllContainLine,lineCertificationEdit,lineCertificationTypeEdit } from './api/api'
export default {
  name: 'FirstLevelParam',
  mixins: [TableMixin],
  data() {
    return {
      visible:false,
      description: '线体认证',
      queryParam: {},
      scrollX: document.body.clientWidth > 1200 ? 'calc(100%)' : 'calc(120px + 100%)',
      url: {
        list: '/api/xxxx',
        delete: '/api/xxxx',
        exportXlsUrl: '/api/xxxx',
        importExcelUrl: '/api/xxxx',
        downTemplateUrl: '/api/ixxx'
      },
      extRender:[],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'rowIndex',
          isShow: true,
          width: 50,
          align: 'center',
          fixed: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '客户代码',
          dataIndex: 'clientCode',
          key: 'clientCode',
          align: 'center',
          width: 80,
           fixed: 'left',
        },
        {
          title: '机型',
          dataIndex: 'series',
          key: 'series',
          align: 'center',
          ellipsis: true,
          width: 240,
          fixed: 'left',
        },
        {
          title: '产品ID',
          dataIndex: 'productId',
          key: 'productId',
          align: 'left',
          width: 140,
          fixed: 'left',
        },
        
        // {
        //   title: 'cqe',
        //   dataIndex: 'cqe',
        //   key: 'cqe',
        //   align: 'center'
        // },
        // {
        //   title: '备注',
        //   dataIndex: 'remark',
        //   key: 'remark',
        //   align: 'center'
        // },

        
      ]
    }
  },
  created :{
    
  },
  components: { lineCertificationModal,editValueModal },
  mounted() {
    listAllContainLine().then(res => {
        if (res.data && res.data.code === 0) {
            var data = res.data.data;
            var x = true;
            data.forEach((item) => {
              x = !x
              var processName = item.processName
              var lines = item.lines
              var obj = {}
              obj.title = processName
              obj.dataIndex = processName
              obj.key = processName
              obj.align = 'center'
              obj.children = []
              obj.className = x ? '' : 'cloumnGreen'

              lines.forEach((line) => {
                  var c_obj = {}
                  var lineDetail = processName +"_"+ line
                  this.extRender.push(lineDetail)
                  c_obj.title = line
                  c_obj.dataIndex = lineDetail
                  c_obj.key = lineDetail
                  c_obj.width = 40 + 'px'
                  c_obj.align = 'center'
                  c_obj.className = obj.className
                  c_obj.scopedSlots = { customRender: lineDetail }
                  obj.children.push(c_obj)
              })

              this.columns.push(obj)
            })
            this.columns.push(
              {
                title: '操作',
                dataIndex: 'action',
                scopedSlots: { customRender: 'action' },
                width: 120,
                fixed: 'right',
                align: 'center'
            })
        } else {
            this.$message.error({
                content: res.data.msg,
            });
        }
    })

    
  },
  methods: {
    updateType(type,productId,lineDetail){
      console.info(type)
      console.info(productId)
      console.info(lineDetail)
      var param = {
        productId:productId,
        typeDetail:lineDetail,
        certificationType:type,
      }
      this.$refs.editModalForm.edit(param)
      this.$refs.editModalForm.title = '认证'

      // lineCertificationTypeEdit(param).then(res => {
      //   if (res.data && res.data.code === 0) {
      //     this.$message.success({
      //       content: '操作成功',
      //     });
      //     this.searchQuery()
      //   }else {
      //     this.$message.error({
      //         content: res.data.msg,
      //     });
      //   }

      // }
      // )
    },
    // 获取表格行的样式
    getRowClassName(record, index) {
      let className = ''
      className = index % 2 === 0 ? 'evenRow' : 'oddRow'
      return className
    },

    handleOk() {
      this.loadData()
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ th.cloumnRed{
 background-color: #f8cbad !important;
} 

/deep/ th.cloumnGreen{
 background-color: #DCEBFB !important;
 color: #333 !important;
} 
.table-operator{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/.poros-tag-pink {
    color: #FA3F5E;
    background: #FFEDF0;
    border-color: #FA3F5E;
    font-weight: 700;
}

/deep/.poros-tag-green {
    color: #ff760d;
    background: #FFEFE3;
    border-color: #FF760D;
    font-weight: 700;
}

/deep/.poros-btn-link {
    display: inline-block;
    padding-left: 7px;
    width: 100%;
    height: 100%;
    border-radius: 0;
    border-right: 1px solid #dfdede;
}
 /deep/.poros-table-middle > .poros-table-content > .poros-table-scroll > .poros-table-body > table > .poros-table-tbody > tr > td{
   padding: 0;
 }
</style>


import { getAction, downFile, httpAction } from '@/api/manage.js'
import system from '@/config/system'

export const TableMixin = {
  data() {
    return {
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /*排序*/
      isorter:{},
      /* 数据源 */
      dataSource: [],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* table加载状态 */
      loading: false,
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 20,
        pageSizeOptions: ['10', '20', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isMountedLoad: true,
      importLoading: false,
      scrollY: 600, // 表格竖向滚动条,386是页面其他元素的高度
      screenHeight: document.body.clientHeight // 屏幕的高度
    }
  },
  computed: {
    importExcelUrl() {
      return system.devApi + this.url.fileUrl
    }
  },
  // watch: {
  //   // 监听屏幕高度改变表格高度
  //   screenHeight(val) {
  //     // 初始化表格高度
  //     this.scrollY = val - document.getElementsByClassName('poros-table-wrapper')[0].offsetTop - 200
  //   }
  // },
  mounted() {
    if(this.isMountedLoad){
      this.loadData()
    }
    // 计算table 垂直滚动高度
    this.handleTableHeight()
    // 监听屏幕高度
    window.addEventListener('resize', this.handleTableHeight)
  },
  destroyed() {
    window.removeEventListener('resize', this.handleTableHeight)
  },
  methods: {
    //加载列表
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()
      getAction(this.url.list, params).then((res) => {
        let resData = res.data
        if (resData.success && resData.data) {
          //update-begin-  for:适配不分页的数据列表------------
          this.dataSource = resData.data.records || resData.data
          //update-end--- for:适配不分页的数据列表------------
          if (resData.data.total) {
            this.ipagination.total = resData.data.total
          } else {
            this.ipagination.total = 0
          }
        } else {
          this.$message.warning(resData.msg || '服务出错,请稍后重试!')
        }

        this.loading = false
      })
    },

    //获取查询条件
    getQueryParams() {
      var param = Object.assign(this.queryParam)
      param.pageNo = this.ipagination.current
      param.limit = this.ipagination.pageSize
      return param
    },

    // 查询按钮
    searchQuery() {
      this.loadData(1)
    },

    // 重置按钮
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },

    // 选中项发生变化时的回调
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },

    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },

    // 新增
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    // 编辑
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    // 查看详情
    handleDetail(record) {
      this.handleEdit(record)
      this.$refs.modalForm.title = '查看详情'
      this.$refs.modalForm.disableSubmit = true
    },
    /* 新增编辑后重载列表 */
    modalFormOk() {
      this.loadData()
    },
    /* 删除 */
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      // getAction(that.url.delete, { id: id }).then((res) => {
      httpAction(that.url.delete, id, 'delete').then((res) => {
        if (res.data.success) {
          that.$message.success('删除成功' || res.data.msg)
          that.loadData()
        } else {
          that.$message.warning(res.data.msg)
        }
      })
    },

    // 获取表格行的样式
    getRowClassName(record, index) {
      let className = ''
      className = index % 2 === 0 ? 'evenRow' : 'oddRow'
      return className
    },
    /* 导出 */
    handleExportXls2() {
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()))
      let url = `${system.devApi}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`
      window.location.href = url
    },

    /* 下载模板 */
    handleDownTemplate() {
      window.location.href = this.url.downTemplateUrl
    },

    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let { limit, pageNo, ...param } = this.queryParam
      // let param = this.getQueryParams()
      // if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
      //   param['selections'] = this.selectedRowKeys.join(',')
      // }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((res) => {
        let data = res.data
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel(info) {
      this.importLoading = true
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.importLoading = false
        let response = info.file.response
        if (response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (response.code !== 0) {
            let {
              message,
              result: { msg, fileUrl, fileName }
            } = info.file.response
            let href = system.devApi + fileUrl
            this.$message.info({
              title: message,
              content: (
                <div>
                  <span>{msg}</span>
                  <br />
                  <span>
                    具体详情请{' '}
                    <a href={href} target="_blank" download={fileName}>
                      点击下载
                    </a>{' '}
                  </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.msg || `${info.file.name} 文件上传成功`)
            this.loadData()
            // let { data } = info.file.response
            // if (data && Object.keys().length > 0) {
            //   this.importResult = data
            // }
          }
        } else {
          this.$message.error(info.file.response.msg || '导入模板错误!')
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
        this.importLoading = false
      }
    },
    // table 可滚动高度设置
    handleTableHeight() {
      // let tableDoms = document.getElementsByClassName('poros-table-wrapper') || []
      // let tableOffsetTop = tableDoms.length > 0 ? tableDoms[0].offsetTop : 100
      // this.screenHeight = document.body.clientHeight
      // this.scrollY = this.screenHeight - tableOffsetTop - 194

      let tableDom = this.$refs['table']?.$el
      let tableDomTop = tableDom.getBoundingClientRect().top + 80
      this.screenHeight = document.body.clientHeight
      // tableTitleColumns 表示 表头的行数
      this.scrollY = this.screenHeight - tableDomTop - (this.tableTitleColumns || 1) * 40
    }
  }
}


image.png