Vue3 Antd table表格单选全选,选中数据翻页失效问题

357 阅读1分钟

table绑定row-selection 建议粘贴复制,代码可以自己优化


<a-table
        :row-selection="{
        selectedRowKeys: state.selectedRowKeys,
        preserveSelectedRowKeys:true, //没啥用感觉,可以不要这一行,自己可以查查
        onSelect: (record:any) => {
          onSelectChange(record.id)
        },
        onSelectAll:onSelectAllChange,
        selections: [
            {
                key: 'clear',
                text: '清空所有',
                onSelect: () => {
                state.selectedRowKeys = []
                },
            },
            ],
      }"

具体绑定的函数和选中值 粘贴复制直接用就对了 ts代码可以删了,我是ts新手,不是很会定义的类型


type Key = string | number
interface State {
  selectedRowKeys: Key[]
  loading: boolean
}
// table选中表格
const state = reactive<State>({
  selectedRowKeys: [], 
  loading: false,
})


//--------------------- 可以不要
const hasSelected = computed(() => state.selectedRowKeys.length > 0) //所有选中的数量
  
  <template v-if="hasSelected">
          {{ `已选择 ${state.selectedRowKeys.length} 项` }}
  </template>

//---------------------可以不要

const onSelectChange = (id: any) => {
    // 我是需要id作为值
  const index = state.selectedRowKeys.findIndex((item) => item === id)
  if (index !== -1) {
    state.selectedRowKeys.splice(index, 1)
  } else {
    state.selectedRowKeys = state.selectedRowKeys.concat(id)
  }
}
const onSelectAllChange = (selected: boolean, selectedRows: any, changeRows: any) => {
    // 我是需要id作为值
  const ids = changeRows.map((item: { id: number }) => item.id)
  if (selected) {
    state.selectedRowKeys = state.selectedRowKeys.concat(ids)
  } else {
      //without 需要安装lodash库
      //import { without } from 'lodash'
    state.selectedRowKeys = without(state.selectedRowKeys, ...ids)
  }
}