antd vue table 公共方法

252 阅读1分钟
<p-table
    ref="table"
    rowKey="id"
    size="middle"
    :rowClassName="getRowClassName"
    :columns="columns"
    :dataSource="dataSource"
    :pagination="ipagination"
    :loading="loading"
    @change="handleTableChange"
    :scroll="{ x: 1500, y: scrollY }"
    >
    <template v-for="item in columns" :slot="item.slotName">
      <span class="d-block ellipsis" :key="index" :title="$t(item.slotName)">{{ $t(item.slotName) }}</span>
    </template>
 </p-table>
      
import { getAction, downFile, httpAction } from '@/api/manage.js'
import system from '@/config/system'

export const TableMixin = {
  data() {
    return {
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 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
          if (this.needChildren) {
            this.dataSource = (this.dataSource || []).map((item) => {
              item.children = item.children || []
              item.isParent = true
              return item
            })
          }
          //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)
        }
      })
    },

    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },

    // 获取表格行的样式
    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.getQueryParams()
      // 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 + '.xlsx')
        } 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 + '.xlsx')
          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() {
      // console.log(this.$refs['table'].$el.offsetTop)
      // let tableDoms = document.getElementsByClassName('poros-table-wrapper') || []
      // let tableOffsetTop = tableDoms.length > 0 ? tableDoms[0].offsetTop : 100
      let tableOffsetTop = this.$refs['table']?.$el?.getBoundingClientRect().top || 180
      this.screenHeight = document.body.clientHeight
      this.scrollY = this.screenHeight - tableOffsetTop - 76 - (this.tableTitleColumns || 1) * 40
    },
    doc(record) {
    }
  }
}