antd-vue table 分页缓存已勾选数据

<a-table
  size="small" bordered
  rowKey={this.rowKey}
  row-selection={{
    type: this.selectType,
    selectedRows: this.selectedRows,
    selectedRowKeys: this.selectedRowKeys,
    onChange: this.handleSelectChange.bind(this),
  }}
  scroll={ { y: 600 } } pagination={true}
  pagination={this.pagination}
  on-change={this.tableChange}
  data-source={this.tableData}
  columns={columns.call(this, h)}
  {...{ scopedSlots: this.scopedSlotsList }}
/>

分页

<a-table
  ......
  scroll={ { y: 600 } } pagination={true}
  pagination={this.pagination}
  on-change={this.tableChange}
  ......
/>

分页配置

pagination: {
  total: 0, // 数据总数
  current: 1, // 当前页数
  defaultPageSize: 100, // 默认每页显示10条数据
  showTotal: null, // 展示总共有几条数据
  showSizeChanger: false, // 显示修改pageSize的下拉框
  pageSizeOptions: ['100'], // 设置pageSize的可选值,页面可以通过下拉框进行选择
  onShowSizeChange: (current, pageSize) => {
    this.pageSize = pageSize
  }
},

数据请求

async getList (paging) {
  if (!this.method) return
  if (!this.init) {
    return {
      rows: [],
    }
  }
  const fn = this.method
  const { data = {} } = await fn({
    ...this.paramValue,
    ...this.cacheQuery,
    ...paging,
    pageSize: this.pageSize,
    currentNo: this.pagination.current,
  })

  let rows = ([...data.rows] || []).map(item => {
    // 缓存 已勾选的数据
    if (this.selectedRowKeys.length && this.selectedRowKeys.includes(item[this.rowKey])) {
      const { qcAssistQty, qcMainQty } = this.selectedRows.find(row => row[this.rowKey] === item[this.rowKey])
      return {
        ...item,
        qcAssistQty: qcAssistQty || 0,
        qcMainQty: qcMainQty || 0,
      }
    }
    return {
      ...item,
      qcAssistQty: item.assistQty || item.inInventoryAssistQty || 0,
      qcMainQty: item.mainQty || item.inInventoryQty || 0,
    }
  })
  this.tableData = rows
  this.pagination.total = data.totalElements || 0 // 总页数
  return { ...data, data: { rows } }
},

分页方法

tableChange (pagination, filters, sorter) {
  this.pagination = pagination
  this.getList()
},

搜索查询

handleSearch (query = {}) {
  this.init = true
  this.cacheQuery = { ...query }
  this.pagination.current = 1
  this.handleRefresh()
},

// 刷新数据
handleRefresh () {
  this.init = true
  this.clearSelected()
  this.getList()
},

// 清空勾选数据
clearSelected () {
  this.handleSelectChange([], [])
},

勾选数据

通过 rowSelection.selectedRowKeys 来控制选中项; 通过 rowSelection.selectedRows 来控制选择行数据, 当然我们也可以使用 rowSelection.selections 自定义选择配置项, 设为 true 时使用默认选择项.

对于带有分页的 table 数据, 如何处理勾选数据呢?

由于 selectedRowKeys 可以记录所有勾选的数据的 ID, 而 selectedRows 只会记录当前页选中项.

handleSelectChange (selectedRowKeys, selectedRows) {
  this.updateSelect(selectedRowKeys, selectedRows)
  this.$emit('select', this.selectedRows)
},
// 缓存已勾选的 selectedRows
updateSelect (selectedRowKeys, selectedRows) {
  let keyLength = selectedRowKeys.length
  let rowLength = this.selectedRows.length
  if (keyLength > rowLength) {
    // 不添加重复项
    selectedRows.forEach((row) => {
      let idx = this.selectedRows.findIndex((item) => item[this.rowKey] === row[this.rowKey])
      if (idx === -1) {
        this.selectedRows.push(row)
      }
    })
  } else {
    // 剔除反选项
    this.selectedRows = this.selectedRows.reduce((list, row) => {
      if (selectedRowKeys.includes(row[this.rowKey])) {
        list.push(row)
      }
      return list
    }, [])
  }
  this.selectedRowKeys = [...new Set(selectedRowKeys)]
},

默认勾选

通过 rowSelection.getCheckboxProps 来配置选择框的默认属性配置.

<a-table
  ....
  row-selection={{
    getCheckboxProps: record => {
      return {
        props: {
          defaultChecked: this.selectedRowKeys.includes(record[this.rowKey]),
        },
      }
    },
    selectedRowKeys: this.selectedRowKeys,
    onChange: this.handleSelectChange.bind(this),
  }}
  ......
/>

在初始化数据的时候, 我们需要添加选中的项.

async getInit () {
  if (!this.id) return
  const { data } = await Allocate.getDetail({ id: this.id })
  const list = data.details
  this.selectedRows = list
  this.selectedRowKeys = list.filter(item => item.age > 17).map(item => item[this.rowKey])
},

勾选数据 table 列校验

computed: {
  // 异步规则
  asyncRules () {
    return function (record, key) {
      if (this.selectedRowKeys.includes(record[this.rowKey])) {
        return {
          validator: (rule, value, callback) => {
            return this.handleRule(key, value, record, callback)
          },
        }
      }
    }
  },
  // 作用域插槽
  scopedSlotsList () {
    const obj = {}
    Array.prototype.forEach.call(['qcAssistQty', 'qcMainQty'], item => {
      obj[item] = (text, record, index) => {
        return <cell-validate mode="a-input-number" class="w140"
          validateProp={`${item}${index}`}
          validators={validators}
          rules={this.asyncRules(record, item)}
          v-model={this.tableData[index][item]} />
      }
    })
    return obj
  },
},

校验规则

handleRule (key, value, record, callback) {
  if (Number(value) === 0) {
    return callback(new Error('数量不能为0'))
  }
  if (!Reg.numUnit(value)) {
    return callback(new Error('最多保留六位小数'))
  }
  if (this.modal === 'orderQuality') { // 在库
    if (key === 'qcAssistQty') {
      if (Number(value) > record.inInventoryAssistQty) {
        return callback(new Error(`数量不超过${record.inInventoryAssistQty}`))
      }
    } else if (key === 'qcMainQty') {
      if (Number(value) > record.inInventoryQty) {
        return callback(new Error(`数量不超过${record.inInventoryQty}`))
      }
    }
  } else if (['orderRev', 'orderIn'].includes(this.modal)) { // 收货明细、质检登记
    // ......
  }
  return callback()
},

对勾选数据校验(包含非当前页勾选数据)。

// 对勾选数据校验
async handleSelectValidate () {
  const length = this.selectedRows.length
  // 未勾选,无需校验
  if (length === 0) {
    return Promise.resolve(true)
  }
  for (let index = 0; index < length; index++) {
    const rows = this.selectedRows[index]
    for await (let key of Object.keys(rows)) {
      if (['qcAssistQty', 'qcMainQty'].includes(key)) {
        try {
          await this.handleRule(key, rows[key], rows, function (err) {
            if (err) {
              throw new Error(err)
            }
          })
        } catch (error) {
          return Promise.resolve(false)
        }
      }
    }
  }
  return Promise.resolve(true)
},

你可能感兴趣的:(ant-design-vue,antd-vue,table,缓存勾选数据,校验)