Skip to content

Sorting ​

Sorting revolves around these fields: sorter, sortOrder, defaultSortOrder and sortDirections.

If you come from ant-design-vue, this will look familiar. The difference is that vtable-guild puts more emphasis on column sorting that works out of the box, and funnels sorting results into the change event.

Live demo ​

Single-column, multi-column and custom compare functions in one table. Click a header to toggle sorting, and click the columns that set sorter.multiple one after another to stack sorts.

Edit in Playground

How to enable sorting ​

  • sorter: true uses the default comparison rules. Numbers are sorted by value, and other values are compared as strings.
  • sorter: (a: TRecord, b: TRecord) => number uses a custom compare function; TRecord is the row data type.
  • sorter: { multiple: number } enables multi-column sorting and sets the priority.
  • defaultSortOrder sets the default sort direction when the column is first initialized.
  • sortOrder enters controlled mode, where external state decides the current sort direction.

The most common usage ​

vue
<script setup lang="ts">
import { VTable, type TableColumnsType } from '@vtable-guild/vtable-guild'

interface ScoreRow {
  key: string
  name: string
  score: number
}

const columns: TableColumnsType<ScoreRow> = [
  { title: 'Name', dataIndex: 'name', key: 'name' },
  {
    title: 'Score',
    dataIndex: 'score',
    key: 'score',
    align: 'right',
    sorter: true,
  },
]

const dataSource: ScoreRow[] = [
  { key: '1', name: 'Charlie', score: 80 },
  { key: '2', name: 'Alice', score: 95 },
]
</script>

<template>
  <VTable row-key="key" :columns="columns" :data-source="dataSource" />
</template>

Controlled sorting ​

When the sorting state has to stay in sync with page query parameters, server requests or external state, controlled mode is the more reliable choice.

ts
import { computed, ref } from 'vue'
import type { SortOrder, TableColumnsType, VTableEventProps } from '@vtable-guild/vtable-guild'

const scoreOrder = ref<SortOrder>('ascend')

const columns = computed<TableColumnsType<ScoreRow>>(() => [
  { title: 'Name', dataIndex: 'name', key: 'name' },
  {
    title: 'Score',
    dataIndex: 'score',
    key: 'score',
    sorter: true,
    sortOrder: scoreOrder.value,
  },
])

const handleChange: NonNullable<VTableEventProps<ScoreRow>['onChange']> = (_filters, sorter) => {
  const results = Array.isArray(sorter) ? sorter : [sorter]
  scoreOrder.value = results.find((result) => result.columnKey === 'score')?.order ?? null
}

Reuse the ScoreRow above and bind @change="handleChange" on the table. VTableEventProps<ScoreRow>['onChange'] provides the complete event parameter types, and NonNullable removes the undefined of the optional event prop. A single-column result is an object and a multi-column result is an array, so narrow it with Array.isArray before reading. In controlled mode, whether to update sortOrder is up to you.

Server-side sorting ​

sorter: true uses the local default comparator; a controlled sortOrder does not disable local sorting automatically either. When the server has already sorted the data, also enable manual.sort to keep the order of the returned records:

vue
<VTable
  row-key="key"
  :columns="columns"
  :data-source="dataSource"
  :manual="{ sort: true }"
  @change="handleChange"
/>

The sort controls, the single-column and multi-column state and the change event keep working; your application queries again when extra.action === 'sort'. You can also use useTableRequest to manage server-side sorting, filtering, pagination and refreshing in one place.

For local sorting with remote filtering or pagination, see Choose where data is processed and the mixed example. Setting only manual.sort to false does not stop a connected Hook onChange from requesting; event connections and sort state must also match the chosen setup.

Multi-column sorting ​

When several fields need to take part in sorting, use multiple to set the priority. The larger the number, the higher the priority.

ts
import type { TableColumnsType } from '@vtable-guild/vtable-guild'

interface TeamScoreRow {
  key: string
  age: number
  team: string
  score: number
}

const columns: TableColumnsType<TeamScoreRow> = [
  { title: 'Age', dataIndex: 'age', key: 'age', sorter: { multiple: 1 } },
  { title: 'Team', dataIndex: 'team', key: 'team', sorter: { multiple: 2 } },
  { title: 'Score', dataIndex: 'score', key: 'score', sorter: { multiple: 3 } },
]

Practical usage tips ​

  • For simple sorting prefer sorter: true, so you do not write compare functions again and again for ordinary number and string fields.
  • If the page also has filtering, the current data processing order is filter first, then sort, so multi-column sorting runs on the filtered result.
  • If you plan to work with the server, enable manual.sort; when sorting has to be reset from outside, also bind a controlled sortOrder so the header and the request state stay consistent.

API ​

TRecord is your application's row type. The tables below list only the sorting-related configuration; for all props see the API Reference.

Props ​

PropTypeDefaultDescription
showSorterTooltipboolean | TableTooltipConfigtrue for antdv, false for element-plusTable-level sorter tooltip config; a column-level showSorterTooltip overrides it.
sortDirectionsSortOrder[]['ascend', 'descend']Table-level list of sort directions, used as the default for column-level sortDirections.
manualboolean | TableManualConfigfalsetrue skips local sorting, filtering and pagination slicing; the object form sets sort, filter and pagination separately, with omitted fields treated as false. Controls local computation only; it neither sends nor prevents requests. Header state and the change event keep working; see Choosing a processing mode.

Column fields ​

FieldTypeDefaultDescription
sorterColumnSorter<TRecord>-Enables sorting; supports the default comparison, a custom compare function and a multi-column sort object.
sortOrderSortOrder-Controlled sort direction.
defaultSortOrderSortOrder-Sort direction an uncontrolled column is initialized with.
sortDirectionsSortOrder[]Inherits the table-level settingSort directions available for this column. An empty array falls back to ['ascend', 'descend'].
showSorterTooltipboolean | TableTooltipConfigInherits the table-level settingColumn-level sorter tooltip switch and config.

Events ​

EventPayloadDescription
change(filters: TableFiltersInfo, sorter: VTableSorterResult<TRecord>, extra: TableChangeExtra<TRecord>) => voidSingle event outlet after sorting, filtering, selection and pagination; extra.action is 'sort', 'filter', 'select' or 'paginate'.

When sorting triggers, extra.action is 'sort' and extra.currentDataSource is the processed data before pagination. sorter is an array when more than one sort column is active, and an object otherwise. With controlled sorting, sorter reflects the sort requested by this operation, while extra.currentDataSource is still computed from the sortOrder currently passed in.

Theming ​

To change only colors, override the CSS variables first; to change classes, use the per-instance ui or the global theme.table.slots. For how to choose between the three, see Three-layer theme overrides.

ui slots ​

SlotDescription
thSortableExtra styles for the <th> of sortable columns.
thSorted<th> background of the actively sorted column.
tdSorted<td> background of the actively sorted column.
sortButtonSort icon container.
sortIconDownSpacing adjustment for the descending icon.
sortAreaOuterOutermost flex wrapper of the sort area.
sortAreaWrapperFlex wrapper between the title and the sort icon.
sortAreaTitleSort title text container.

Preset defaults ​

The default classes of the two presets on the slots above, given in the structure of createVTableGuild({ theme }); copy and modify them as needed. Override values are merged with the defaults through cn(). In the default precompiled mode these utilities carry the vtg- prefix at runtime; for the override rules see Utility prefix and override rules.

ts
createVTableGuild({
  theme: {
    table: {
      slots: {
        thSortable: 'cursor-pointer select-none hover:bg-[color:var(--vtg-table-header-sort-hover-bg)]',
        thSorted: 'bg-[color:var(--vtg-table-header-sort-bg)] before:!bg-transparent',
        tdSorted: 'bg-[color:var(--vtg-table-body-sort-bg)]',
        sortButton: 'inline-flex shrink-0 flex-col items-center justify-center text-xs leading-none ml-1',
        sortIconDown: '-mt-[0.225em]',
        sortAreaOuter: 'flex flex-auto min-w-0',
        sortAreaWrapper: 'flex flex-auto items-center justify-between min-w-0',
        sortAreaTitle: 'flex-1 min-w-0',
      },
    },
  },
})
ts
createVTableGuild({
  themePreset: 'element-plus',
  theme: {
    table: {
      slots: {
        thSortable: 'cursor-pointer select-none',
        thSorted: '',
        tdSorted: '',
        sortButton: 'inline-flex shrink-0 flex-col items-center justify-center text-xs leading-none ml-1',
        sortIconDown: '-mt-[5px]',
        sortAreaOuter: 'flex min-w-0',
        sortAreaWrapper: 'flex items-center min-w-0',
        sortAreaTitle: 'min-w-0',
      },
    },
  },
})

CSS variables ​

The tables show the default values in light mode; dark mode overrides them separately under .dark.

VariablePurposeantdvelement-plus
--vtg-table-header-sort-hover-bgHover background of sortable headersrgb(0 0 0 / 4%)not read
--vtg-table-header-sort-bgHeader background of the actively sorted column#f0f0f0not read
--vtg-table-body-sort-bgCell background of the actively sorted column#fafafanot read
--color-sorter-iconInactive color of the sort iconrgb(0 0 0 / 29%)#a8abb2

Type Declarations ​

TRecord is your application's row type. The declarations below cover the column sorting configuration and the change event. The column configuration is an excerpt of the related fields; SortingColumnFields is a documentation helper interface, not a package export. For the complete declarations and how to import them, see the Type reference.

View type declarations
ts
export type SortOrder = 'ascend' | 'descend' | null
ts
export type SorterFn<TRecord = Record<string, any>> = (a: TRecord, b: TRecord) => number
ts
export interface ColumnSorterObject<TRecord = Record<string, any>> {
  compare?: SorterFn<TRecord>
  multiple?: number
}
ts
export type ColumnSorter<TRecord = Record<string, any>> =
  | boolean
  | SorterFn<TRecord>
  | ColumnSorterObject<TRecord>
ts
/** ColumnType 节选;文档辅助接口,不是包导出。 */
export interface SortingColumnFields<TRecord extends object = Record<string, any>> {
  key?: Key
  sorter?: ColumnSorter<TRecord>
  sortOrder?: SortOrder
  defaultSortOrder?: SortOrder
  sortDirections?: SortOrder[]
  showSorterTooltip?: boolean | TableTooltipConfig
}
ts
export interface SorterResultLike<TRecord extends object = Record<string, any>> {
  column: ColumnType<TRecord> | undefined
  columnKey: Key | undefined
  order: SortOrder
  field: ColumnType<TRecord>['dataIndex']
}
ts
export type VTableSorterResult<TRecord extends object = Record<string, any>> =
  | SorterResultLike<TRecord>
  | Array<SorterResultLike<TRecord>>
ts
export type TableFiltersInfo = Record<string, (string | number | boolean)[] | null>
ts
export interface TableChangeExtra<TRecord extends object = Record<string, any>> {
  action: 'sort' | 'filter' | 'select' | 'paginate'
  /** Available only when pagination is enabled. */
  pagination?: TablePaginationState
  currentDataSource: TRecord[]
}
ts
export interface VTableEventProps<TRecord extends object = Record<string, any>> {
  onChange?: (
    filters: TableFiltersInfo,
    sorter: VTableSorterResult<TRecord>,
    extra: TableChangeExtra<TRecord>,
  ) => void
  onResizeColumn?: (column: ColumnType<TRecord>, width: number) => void
  onRowDragEnd?: (newData: TRecord[], info: RowDragSortInfo) => void
}