ant-design-vue3.x Table本地查询、分页多选的解决方法

254 阅读1分钟

本范例适用于一次性获取table数据,并做本地分页,进行查询和多选。其他UI组件也可以参考。 antdv的table有本地分页,多选也能在翻页后保持,但如果加了本地筛选查询,在刷新table数据的时候,多选数据会被干扰,因此增加了一个响应式变量来存储所有的多选项。 废话不多说,上代码:

<template>
  <a-form
    ref="formRef"
    :model="formData"
    :labelCol="{ style: { width: '90px' } }">
    <a-form-item label="编号" name="id">
      <a-input autocomplete="off" placeholder="请输入编号" v-model:value="formData.id" />
    </a-form-item>
    <a-form-item colon label="名称" name="name">
      <a-input autocomplete="off" placeholder="请输入名称" v-model:value="formData.name" />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" @click="handleSearch">
        查询
      </a-button>
    </a-form-item>
  </a-form>
  <div>已选择 {{allSelectedRowKeys.length}} 条数据</div>
  <a-table
    rowKey="id" 
    :row-selection="rowSelection"
    :data-source="tableData"
    :columns="columns"/>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { TableColumnsType, TableProps } from 'ant-design-vue'
interface tablData{
  id: number;
  name: string;
}
const data = [...Array(100)].map((_, i) => ({
  id: i,
  name: `T${i}`
}))
// 查询表单
const formData = reactive({
  id:'',
  name:'',
})
// 表格数据
const tableData = ref<tablData[]>(data)
// 原始数据
const rawTableData = ref<tablData[]>(data)
// 表格列
const columns = ref<TableColumnsType>([
  {title:'编号', dataIndex: 'id'},
  {title:'名称', dataIndex: 'name'}
])
// 当前表格数据多选项
const selectedRowKeys = ref<string[]>([])
// 全局表格数据多选项
const allSelectedRowKeys = ref<string[]>([])

const rowSelection: Ref<TableProps['rowSelection']> = ref({
  selectedRowKeys: selectedRowKeys,
  onChange: (sks: string[]) => {
    selectedRowKeys.value = sks
  },
  onSelect: (record:tablData, selected:boolean) => {
    if(selected) {
      if(allSelectedRowKeys.value.indexOf(record.id) == -1) {
        allSelectedRowKeys.value.push(record.id)
      }
    } else {
      allSelectedRowKeys.value = allSelectedRowKeys.value.filter((v:string) => v !== record.id)
    }
  }
})

const handleSearch = () => {
  const searchedData = rawTableData.value.filter((v:tablData) => v.id.indexOf(formData.id) !== -1 && v.name.indexOf(formData.name) !== -1 )
  tableData.value = searchedData
  selectedRowKeys.value = []
  searchedData.forEach((item:tablData) => {
    if(allSelectedRowKeys.value.indexOf(item.id) > -1){
      selectedRowKeys.value.push(item.id)
    }
  })
}
</script>