Skip to content

常见用法

1. 静态数据 + 前端分页

vue
<XTable :columns="columns" :data="data" :pagination="true" border />

组件内部自动按 pageSize 切片,无需额外处理。

2. 远程数据(无分页)

ts
const fetchFn: FetchFn<User> = async (params) => {
  const res = await http.get('/api/users', { params })
  return { data: res.list, total: res.total }
}
vue
<XTable :columns="columns" :fetch-fn="fetchFn" @register="tableApi.register" />

首次需手动调用:

ts
const tableApi = useXTableApi<User>()
onMounted(() => tableApi.value.fetchData())

3. 远程分页

vue
<XTable
  :columns="columns"
  :fetch-fn="fetchFn"
  :pagination="{ pageSize: 10, pageSizes: [10, 20, 50] }"
  @register="tableApi.register"
/>

翻页 / 切换条数时,组件自动把 page / pageSize 注入到 queryParams 中再调用 fetchFn,后端收到的 params 形如:

json
{ "page": 2, "pageSize": 20, "name": "张三" }

4. 多级表头

ts
const columns: ColumnConfig<User>[] = [
  { prop: 'id', label: 'ID' },
  {
    prop: 'salary',
    label: '薪资',
    children: [
      { prop: 'base', label: '基本工资' },
      { prop: 'bonus', label: '奖金' },
    ],
  },
]

5. 选择 + 事件监听

ts
const tableApi = useXTableApi<User>()

tableApi.value.event['selection-change'] = (rows: User[]) => {
  console.log('选中:', rows)
}
vue
<XTable :columns="columns" :data="data" @register="tableApi.register" />

6. 动态组件 + 条件样式

ts
const columns: ColumnConfig<User>[] = [
  {
    prop: 'status',
    label: '状态',
    componentType: 'el-tag',
    componentProps: (row) => ({
      type: row.status === 1 ? 'success' : 'danger',
    }),
  },
]

7. 展开行

ts
const columns: ColumnConfig<User>[] = [
  { prop: '__expand', label: '', type: ColumnType.Expand, slotName: 'detail' },
  { prop: 'name', label: '姓名' },
]
vue
<XTable :columns="columns" :data="data">
  <template #detail="{ row }">
    <div>详情:{{ row.description }}</div>
  </template>
</XTable>

8. 查询 + 重置分页

ts
const tableApi = useXTableApi<User>()

// 设置查询参数并重置到第 1 页请求
function search(form: QueryForm) {
  tableApi.value.setQueryParams(form)
  tableApi.value.resetPagination()
}

Released under the MIT License.