Table
Display rows with sorting, selection, fixed headers and columns, nested headers, tree data, expandable rows, summaries, merged cells and custom content.
Import
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableRowData } from '@nscode/handy-ui'
Basic usage, stripes and borders
Each column's prop reads a field from the row. Provide a stable, unique row-key for rows. Without columns, fields from the first row are used automatically.
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'Alex', age: 28 },
{ id: 2, name: 'Sam', age: 32 },
{ id: 3, name: 'Taylor', age: 25 }
]
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: 'Name' },
{ prop: 'age', label: 'Age', align: 'right' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>Default</p>
<HuiTable :data="data" :columns="columns" />
</div>
<div>
<p>stripe</p>
<HuiTable :data="data" :columns="columns" stripe />
</div>
<div>
<p>border</p>
<HuiTable :data="data" :columns="columns" border />
</div>
</HuiSpace>
</template>
Nested fields and custom values
prop accepts paths such as product.name and items[0].qty. A literal key with the same name takes precedence, including an explicit undefined. Missing intermediate values return undefined.
Use accessor(row) for a computed value. It takes precedence over prop. Display, formatter, default sorting and default summaries share this raw value; formatting does not change the sort or summary input. Custom sortMethod and summaryMethod still receive the original row data. Keep accessors pure.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const data = ref([
{ id: 1, product: { name: 'Notebook' }, items: [{ qty: 2 }], price: 6 },
{ id: 2, product: { name: 'Pen' }, items: [{ qty: 3 }], price: 2 }
])
const columns: TableColumnConfig[] = [
{ prop: 'product.name', label: 'Product' },
{ prop: 'items[0].qty', label: 'Quantity', sortable: true },
{
prop: 'amount',
label: 'Amount',
accessor: (row) => row.items[0].qty * row.price,
formatter: (_row, _column, value) => `${value} units`,
sortable: true
}
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="data[0].items[0].qty++">Add one notebook</HuiButton>
<HuiTable :data="data" :columns="columns" show-summary border />
</HuiSpace>
</template>
The prop remains the column identity for sorting, resizing and slots. Use dynamic slot names for dotted fields: #[`product.name`]="{ row }" or #[`header-product.name`] for the header.
Sizes and alignment
Sizes are large, default and small. They use 16, 12 and 8px cell padding respectively. Column alignment supports left, center and right; unset group-header alignment is centered.
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSize } from '@nscode/handy-ui'
const sizes: TableSize[] = ['large', 'default', 'small']
const data = [{ id: 1, left: 'Left', center: 'Center', right: 100 }]
const columns: TableColumnConfig[] = [
{ prop: 'left', label: 'left', align: 'left' },
{ prop: 'center', label: 'center', align: 'center' },
{ prop: 'right', label: 'right', align: 'right' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<div v-for="size in sizes" :key="size">
<p>{{ size }}</p>
<HuiTable :data="data" :columns="columns" :size="size" border />
</div>
</HuiSpace>
</template>
Content-based column widths
Use tableLayout="auto" to size columns from their content. Cells stay on one line, overflow is clipped with an ellipsis, and a table wider than its container scrolls horizontally. The same data below compares both layouts. Column maxWidth only applies to auto; showOverflowTooltip displays clipped body text on hover.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableLayout } from '@nscode/handy-ui'
const layouts: TableLayout[] = ['fixed', 'auto']
const longer = ref(false)
const data = ref([
{
id: 1,
name: 'Short name',
description:
'A long office address with building, street and district details to demonstrate clipping after the maximum width',
amount: 12
},
{
id: 2,
name: 'A considerably longer second name',
description: 'Pudong, Shanghai',
amount: 25
}
])
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name: min 100 / max 160', minWidth: 100, maxWidth: 160, fixed: 'left' },
{
prop: 'description',
label: 'Address: max 16rem',
maxWidth: '16rem',
showOverflowTooltip: true
},
{ prop: 'amount', label: 'Amount: width 110', width: 110, align: 'right' }
]
const changeContent = () => {
longer.value = !longer.value
data.value[1].name = longer.value
? 'An in-place update that also remeasures the sticky column offsets'
: 'Short name'
}
</script>
<template>
<HuiSpace direction="vertical" fill style="max-width: 640px">
<HuiButton @click="changeContent">Change name length</HuiButton>
<div v-for="layout in layouts" :key="layout">
<p>{{ layout }}</p>
<HuiTable :data="data" :columns="columns" :table-layout="layout" border show-summary />
</div>
</HuiSpace>
</template>
An explicit width, including a width saved after resizing, sets the cell's width, minimum and maximum and takes precedence over minWidth and maxWidth. Definite content limits subtract cell padding and the column border. Widths containing % apply only to the cell; the content box uses max-width:100% without applying the percentage again. Tree indentation, expand arrows and sorting icons share the remaining space. Group header width comes from its leaf columns rather than its own width settings.
Native automatic table layout can distribute spare space to fill the container, so the actual th or td may be wider than the declared width or maximum. The separate content box stays constrained and clips its text. Do not treat maxWidth as an absolute cap on the outer cell box. Prefer definite CSS lengths such as px or rem; percentage lengths depend on native table sizing.
Percentages below participate in native column sizing. Visible content changes remeasure sticky offsets; unused business fields do not trigger a deep traversal or measurement. Native wheel/touch scrolling remains available during loading, while the custom loading button stays interactive.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiTable, HuiSpace, HuiSwitch, HuiButton } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const loading = ref(true)
const data = reactive(
Array.from({ length: 20 }, (_, index) => ({
id: index + 1,
name: `Customer ${index + 1}`,
address: 'Project address and notes',
amount: (index + 1) * 10,
revision: 0
}))
)
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name 20%', width: '20%', fixed: 'left' },
{ prop: 'address', label: 'Address 60%', width: '60%' },
{ prop: 'amount', label: 'Amount 20%', width: '20%' }
]
const rename = () => {
data[0].name += ' (updated)'
}
const updateMetadata = () => {
data[0].revision++
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><span>loading</span><HuiSwitch v-model="loading" /><HuiButton @click="rename"
>Update visible content</HuiButton
><HuiButton @click="updateMetadata">Update unused field</HuiButton
><span>Revision {{ data[0].revision }}</span></HuiSpace
>
<HuiTable
:data="data"
:columns="columns"
table-layout="auto"
:height="240"
:loading="loading"
show-summary
selectable
>
<template #loading
><HuiSpace
><span>Loading; native body scrolling remains available</span
><HuiButton size="small" @click="loading = false">Finish loading</HuiButton></HuiSpace
></template
>
</HuiTable>
</HuiSpace>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const resized = ref('Drag a header edge, or focus its handle and press the arrow keys')
const columns: TableColumnConfig[] = [
{
prop: 'group',
label: 'Details',
children: [
{
prop: 'name',
label: 'Tree name',
maxWidth: 180,
showOverflowTooltip: true,
fixed: 'left'
},
{ prop: 'amount', label: 'Amount', width: '7rem', align: 'right' }
]
},
{ prop: 'remark', label: 'Notes: max 12rem', maxWidth: '12rem', showOverflowTooltip: true }
]
const data = [
{
id: 1,
name: 'A parent node with a long clipped name',
amount: 10,
remark: 'Existing cell and sorting interactions remain available',
children: [
{
id: 2,
name: 'A child node whose indentation also uses the available width',
amount: 5,
remark: 'Indentation and arrows fit inside the content limit'
}
]
}
]
const onResize = (column: TableColumnConfig, width: number) => {
resized.value = `${column.label}: ${width}px, now used as the content width`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable
:data="data"
:columns="columns"
table-layout="auto"
border
selectable
expandable
default-expand-all
show-summary
@column-resize="onResize"
>
<template #expand="{ row }">Current record: {{ row.name }}</template>
</HuiTable>
<span>{{ resized }}</span>
</HuiSpace>
</template>
Sorting and selection
sortable: true sorts the data locally. sortable: 'custom' only updates the arrows and emits sort-change; fetch remote data in that event. Click a sortable header or press Enter or Space to cycle ascending, descending and unsorted. Select rows using the checkbox column.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableRowData, TableSortState } from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'Alex', amount: 120 },
{ id: 2, name: 'Sam', amount: 80 }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name', sortable: 'custom' },
{ prop: 'amount', label: 'Amount', sortable: true }
]
const selected = ref<TableRowData[]>([])
const sort = ref('No sorting')
const onSelection = (rows: TableRowData[]) => {
selected.value = rows
}
const onSort = (value: TableSortState) => {
sort.value = `${value.prop}: ${value.order ?? 'none'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable
:data="data"
:columns="columns"
selectable
@selection-change="onSelection"
@sort-change="onSort"
/>
<span>Selected: {{ selected.length }}; {{ sort }}</span>
</HuiSpace>
</template>
Controlled selection
v-model:selected-keys synchronizes original row keys; numeric keys remain numbers. With selectedKeys supplied, checkbox state and exposed selection follow the parent value. update:selectedKeys requests new keys, followed by select or select-all and selection-change with the proposed rows, even when the parent refuses the update. Assigning keys externally emits no selection events.
Consecutive row toggles, select-all, and clear calls within one tick merge against the latest proposed keys. A parent update becomes the next baseline; if no update is accepted, the next batch starts from the parent value again. Explicit selectedKeys=undefined remains controlled with an empty selection. Removing the property restores its previous internal value; rejected proposals do not replace that value.
<script setup lang="ts">
import type { TableExpose } from '@nscode/handy-ui'
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableRowData } from '@nscode/handy-ui'
const rows = [
{ id: 1, name: 'Alex' },
{ id: 2, name: 'Sam' },
{ id: 3, name: 'Taylor' }
]
const columns = [{ prop: 'name', label: 'Name' }]
const keys = ref<(string | number)[]>([2])
const tableRef = ref<TableExpose>()
const selectEach = () => rows.forEach((row) => tableRef.value?.toggleRowSelection(row, true))
const frozen = [2]
const request = ref('No update requested')
const event = ref('No action yet')
const recordKeys = (value: (string | number)[]) => {
request.value = JSON.stringify(value)
}
const recordRows = (value: TableRowData[]) => {
event.value = value.map((row) => row.name).join(', ') || 'none'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>Automatically accept updates</p>
<HuiTable
ref="tableRef"
v-model:selected-keys="keys"
:data="rows"
:columns="columns"
selectable
/>
<HuiSpace
><HuiButton @click="keys = [1, 3]">Select 1 and 3 externally</HuiButton
><HuiButton @click="selectEach">Select each row in one tick</HuiButton
><span>keys: {{ keys }}</span></HuiSpace
>
</div>
<div>
<p>Record requests without applying them: Sam stays selected.</p>
<HuiTable
:selected-keys="frozen"
:data="rows"
:columns="columns"
selectable
@update:selected-keys="recordKeys"
@selection-change="recordRows"
/>
<p>Requested keys: {{ request }}; proposed rows: {{ event }}</p>
</div>
</HuiSpace>
</template>
Preserve selection across pages
reserve-selection keeps selected keys and previously seen selected rows from other pages. Select All and deselecting the current page only affect current data. Header checked and indeterminate states also only use the current data, including collapsed tree children. clearSelection() clears every page.
<script setup lang="ts">
import type { TableExpose } from '@nscode/handy-ui'
import { computed, ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
const tableRef = ref<TableExpose>()
const page = ref(0)
const pages = [
[
{ id: 1, name: 'Alex' },
{ id: 2, name: 'Sam' }
],
[
{ id: 3, name: 'Taylor' },
{ id: 4, name: 'Jordan' }
]
]
const rows = computed(() => pages[page.value])
const keys = ref<(string | number)[]>([])
const columns = [
{ prop: 'id', label: 'ID' },
{ prop: 'name', label: 'Name' }
]
const names = computed(() =>
keys.value
.map((key) => pages.flat().find((row) => String(row.id) === String(key))?.name)
.filter(Boolean)
.join(', ')
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton :disabled="page === 0" @click="page = 0">Page 1</HuiButton>
<HuiButton :disabled="page === 1" @click="page = 1">Page 2</HuiButton>
<HuiButton @click="tableRef?.toggleAllSelection()">Toggle current page</HuiButton>
<HuiButton @click="tableRef?.clearSelection()">Clear every page</HuiButton>
</HuiSpace>
<HuiTable
ref="tableRef"
v-model:selected-keys="keys"
:data="rows"
:columns="columns"
row-key="id"
reserve-selection
selectable
/>
<span>Page {{ page + 1 }}; keys: {{ keys }}; selected: {{ names || 'none' }}</span>
</HuiSpace>
</template>
Current data replaces cached objects with the same key. Unselected off-page rows are discarded from the cache. Selection exposed through the component ref and internal context is a frozen shallow array copy in key order. Its entries cannot be added or removed, while row objects retain their supplied identity and existing editability. Only known rows appear; unknown keys do not create synthetic row objects. Change selection through key props or selection methods.
Route restoration before data arrives
Enable reserve-selection when restoring keys from a route. Keys may arrive before row data; when matching data is fetched, checkboxes and selection resolve automatically. Without reservation, missing keys are removed only on a data change; changing selectedKeys alone does not trigger removal.
<script setup lang="ts">
import type { TableExpose } from '@nscode/handy-ui'
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableRowData } from '@nscode/handy-ui'
const tableRef = ref<TableExpose>()
const keys = ref<(string | number)[]>([3])
const rows = ref<TableRowData[]>([])
const loading = ref(false)
const status = ref('The route supplied key 3; row data has not arrived yet')
const columns = [
{ prop: 'id', label: 'ID' },
{ prop: 'name', label: 'Name' }
]
const load = async () => {
loading.value = true
try {
await new Promise((resolve) => setTimeout(resolve, 400))
rows.value = [
{ id: 3, name: 'Restored record' },
{ id: 4, name: 'Another record' }
]
status.value = 'Data arrived: key 3 is selected automatically'
} finally {
loading.value = false
}
}
const read = () => {
status.value = `selection: ${tableRef.value!.selection.map((row) => row.name).join(', ') || 'no known rows yet'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton :loading="loading" @click="load">Fetch row data</HuiButton
><HuiButton @click="read">Read selection</HuiButton><span>{{ status }}</span></HuiSpace
>
<HuiTable
ref="tableRef"
v-model:selected-keys="keys"
:data="rows"
:columns="columns"
:loading="loading"
reserve-selection
selectable
/>
<span>keys: {{ keys }}</span>
</HuiSpace>
</template>
Controlled sorting
v-model:sort-state synchronizes { prop, order }, where order is ascending, descending or null. A supplied sortState takes precedence over defaultSort. Header interaction emits update:sortState, then sort-change. The arrows and local row order remain controlled by the supplied value until the parent updates it. Assigning a new state externally emits neither event.
A supplied sortState=undefined remains controlled with no sorting and takes precedence over defaultSort. Removing the property restores the previous internal value. Only columns with sortable: true participate in local sorting. A disabled or omitted sortable setting keeps input order even when the column is selected through sort(), defaultSort or a controlled state.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSortState } from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'Alex', age: 30 },
{ id: 2, name: 'Sam', age: 20 },
{ id: 3, name: 'Taylor', age: 25 }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name' },
{ prop: 'age', label: 'Age', sortable: true }
]
const sort = ref<TableSortState | undefined>({ prop: 'age', order: 'ascending' })
const frozen: TableSortState = { prop: 'age', order: 'ascending' }
const requested = ref('No update requested')
const record = (value: TableSortState) => {
requested.value = `${value.prop} / ${value.order ?? 'none'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>v-model:sort-state applies requested updates</p>
<HuiTable v-model:sort-state="sort" :data="data" :columns="columns" />
<HuiSpace
><HuiButton @click="sort = { prop: 'age', order: 'descending' }"
>Set descending externally</HuiButton
><HuiButton @click="sort = undefined">Clear by assigning undefined</HuiButton
><span>{{ sort?.prop || 'none' }} / {{ sort?.order ?? 'none' }}</span></HuiSpace
>
</div>
<div>
<p>This table keeps ascending order because updates are only recorded, not applied.</p>
<HuiTable
:sort-state="frozen"
:default-sort="{ prop: 'age', order: 'descending' }"
:data="data"
:columns="columns"
@update:sort-state="record"
/>
<p>Latest request: {{ requested }}</p>
</div>
</HuiSpace>
</template>
Sort cycles and local comparison
A column's sortOrders controls its cycle. Omit null to prevent clearing through the header; a single entry always requests that order, and an empty array uses the default cycle. Selecting another column, or a state absent from the cycle, starts at its first entry.
sortMethod(a, b, order) runs only for local sortable:true columns. Return an ascending comparison; the table reverses it for descending order. The order argument supports exceptions such as keeping empty values last in both directions.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type {
TableColumnConfig,
TableRowData,
TableSortOrder,
TableSortState
} from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'Alex', age: 30, score: 90, amount: null },
{ id: 2, name: 'Sam', age: 20, score: 70, amount: 80 },
{ id: 3, name: 'Taylor', age: 25, score: 95, amount: 120 }
]
const compareAmount = (a: TableRowData, b: TableRowData, order: TableSortOrder) => {
const direction = order === 'descending' ? -1 : 1
if (a.amount == null) return b.amount == null ? 0 : direction
if (b.amount == null) return -direction
return Number(a.amount) - Number(b.amount)
}
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name' },
{
prop: 'age',
label: 'Age: ascending/descending',
sortable: true,
sortOrders: ['ascending', 'descending']
},
{ prop: 'score', label: 'Score: descending only', sortable: true, sortOrders: ['descending'] },
{
prop: 'amount',
label: 'Amount: empty last',
sortable: true,
sortMethod: compareAmount,
formatter: (row) => (row.amount == null ? 'Not provided' : String(row.amount))
}
]
const sort = ref<TableSortState>({ prop: '', order: null })
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable v-model:sort-state="sort" :data="data" :columns="columns" />
<span>Current sorting: {{ sort.prop || 'none' }} / {{ sort.order ?? 'none' }}</span>
</HuiSpace>
</template>
Sort and clear methods
sort(prop, order) and clearSort() emit update:sortState without emitting sort-change. When resetting remote sorting, clear the state and perform the query explicitly once. The counter below increases once for each header action, method call or reset. sortState exposed through the component ref is deeply read-only.
<script setup lang="ts">
import type { TableExpose } from '@nscode/handy-ui'
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSortState } from '@nscode/handy-ui'
const tableRef = ref<TableExpose>()
const source = [
{ id: 1, name: 'Alex', age: 30 },
{ id: 2, name: 'Sam', age: 20 },
{ id: 3, name: 'Taylor', age: 25 }
]
const data = ref(source.slice())
const sort = ref<TableSortState>({ prop: '', order: null })
const requests = ref(0)
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name' },
{ prop: 'age', label: 'Age', sortable: 'custom' }
]
const query = () => {
requests.value++
const order = sort.value.order
data.value = order
? source.slice().sort((a, b) => (a.age - b.age) * (order === 'ascending' ? 1 : -1))
: source.slice()
}
const descending = () => {
tableRef.value!.sort('age', 'descending')
query()
}
const reset = () => {
tableRef.value!.clearSort()
query()
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="descending">sort('age', 'descending')</HuiButton
><HuiButton @click="reset">clearSort() and query</HuiButton
><span>{{ requests }} queries</span></HuiSpace
>
<HuiTable
ref="tableRef"
v-model:sort-state="sort"
:data="data"
:columns="columns"
@sort-change="query"
/>
</HuiSpace>
</template>
Loading only the body
loading masks the visible body while keeping headers, summary rows and scrollbars visible and usable. The mask stays in place as the table content scrolls. The existing v-loading directive can still mask the whole table when that is desired.
The mask passes pointer hit testing through, allowing native wheel, touch, and momentum scrolling. The loading tbody is inert, blocking body clicks, keyboard focus, text selection, and accessibility access until loading ends. Headers, summaries, and loading status remain outside that region. Only the actual custom loading content box restores pointer interaction; the rest of the mask stays transparent to input.
This example combines a fixed column, nested headers, scrolling and a summary. Column and group headers can be customized with header-{prop} without removing sorting.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const loading = ref(true)
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name', fixed: 'left', width: 160, sortable: true },
{
prop: 'details',
label: 'Details',
children: [
{ prop: 'amount', label: 'Amount', width: 220, sortable: true },
{ prop: 'description', label: 'Description', width: 500 }
]
}
]
const data = Array.from({ length: 12 }, (_, index) => ({
id: index + 1,
name: `Customer ${index + 1}`,
amount: (index + 1) * 10,
description: 'Scroll to check that the body mask stays below the headers and above the summary.'
}))
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>Loading</span><HuiSwitch v-model="loading" /></HuiSpace>
<HuiTable
:data="data"
:columns="columns"
:loading="loading"
loading-text="Fetching customers"
:height="260"
show-summary
border
>
<template #header-details="{ column }"
><strong>{{ column.label }}</strong></template
>
<template #header-name="{ column }"
><span>{{ column.label }} (sortable)</span></template
>
</HuiTable>
</HuiSpace>
</template>
Empty data during loading
While loading empty data, the table reserves roughly three control rows of body height and renders neither emptyText nor the empty slot. Once loading ends, the normal empty state appears. loadingText defaults to the locale's common loading label; an empty string hides the text.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
const loading = ref(true)
const columns = [
{ prop: 'name', label: 'Name' },
{ prop: 'amount', label: 'Amount' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>Loading</span><HuiSwitch v-model="loading" /></HuiSpace>
<div>
<p>Locale loading text</p>
<HuiTable :data="[]" :columns="columns" :loading="loading" empty-text="No matching records" />
</div>
<div>
<p>loading-text="": icon only</p>
<HuiTable :data="[]" :columns="columns" :loading="loading" loading-text="" />
</div>
</HuiSpace>
</template>
Custom loading content
The loading slot replaces the default spinner and text, centered within the body mask, and may contain business action buttons. Avoid expanding its wrapper across the entire mask, which would block native scrolling. Here, the empty slot is only rendered after loading ends.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiIcon, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
const loading = ref(true)
const columns = [
{ prop: 'name', label: 'Task' },
{ prop: 'progress', label: 'Progress' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>Loading</span><HuiSwitch v-model="loading" /></HuiSpace>
<HuiTable :data="[]" :columns="columns" :loading="loading" border>
<template #loading>
<HuiSpace><HuiIcon name="loading" spin /><span>Preparing the task list…</span></HuiSpace>
</template>
<template #empty><span>No pending tasks</span></template>
</HuiTable>
</HuiSpace>
</template>
Cell content and overflow
Use formatter for text or a slot named after the column prop for custom content. Slot scope contains row, column and rowIndex. show-overflow-tooltip displays overflowing cells on one line and shows their full text on hover; each column can override it. Set border to enable column resizing by dragging a header edge or focusing the resize handle and pressing arrow keys.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable, HuiTag } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'A long customer name that exceeds this column', amount: 120.5, status: 'Ready' }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name', width: 160, minWidth: 100 },
{
prop: 'amount',
label: 'Amount',
align: 'right',
formatter: (row) => `$${Number(row.amount).toFixed(2)}`
},
{ prop: 'status', label: 'Status', width: 120, resizable: false }
]
const event = ref('Resize a header column')
const resized = (column: TableColumnConfig, width: number, previous: number) => {
event.value = `${column.label}: ${previous}px → ${width}px`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="data" :columns="columns" show-overflow-tooltip border @column-resize="resized">
<template #status="{ row }"
><HuiTag type="success">{{ row.status }}</HuiTag></template
>
</HuiTable>
<span>{{ event }}</span>
</HuiSpace>
</template>
Tree data and expandable rows
Rows with children display tree controls. Set treeProps to map other field names. load(row) returns a Promise of child rows; callback-style loaders are not supported. A row explicitly marked isLeaf=false is lazy; true or an absent flag with no children is a leaf. Actual non-empty children take precedence over the flag. expandable adds a separate control for the expand slot; it can coexist with tree data.
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'East region', amount: 100, children: [{ id: 11, name: 'Branch', amount: 60 }] },
{ id: 2, name: 'West region', amount: 80 }
]
const columns = [
{ prop: 'name', label: 'Region' },
{ prop: 'amount', label: 'Amount' }
]
</script>
<template>
<HuiTable :data="data" :columns="columns" expandable default-expand-all show-summary>
<template #expand="{ row }"
><p>Details for {{ row.name }}</p></template
>
</HuiTable>
</template>
Custom cells with confirmed deletion
A cell slot can contain action buttons. This example confirms the exact row and its current content before removing it from the local array. Cancel, close, or Escape keeps every row. Changes to the collection or any row content invalidate a pending confirmation, including changes immediately reversed in the same tick; unmounting the example also invalidates it. Repeated deletion requests are blocked while confirmation is pending. No server deletion is requested.
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import {
HuiButton,
HuiMessage,
HuiMessageBox,
HuiSpace,
HuiTable,
HuiTag
} from '@nscode/handy-ui'
import type { TableColumnConfig, TableRowData } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name', width: 140 },
{ prop: 'status', label: 'Status', width: 120 },
{ prop: 'address', label: 'Address' },
{ prop: 'action', label: 'Actions', width: 140 }
]
const source = [
{ id: 1, name: '张三', status: 'active', address: '北京市朝阳区' },
{ id: 2, name: '李四', status: 'disabled', address: '上海市浦东新区' },
{ id: 3, name: '王五', status: 'active', address: '广州市天河区' }
]
const data = ref(source.slice())
const removing = ref(false)
let revision = 0
let alive = true
watch(data, () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
const remove = async (row: TableRowData) => {
const target = data.value.find((item) => item === row)
if (!alive || removing.value || !target) return
const collection = data.value
const version = revision
removing.value = true
try {
await HuiMessageBox.confirm(
'Delete row “' + target.name + '” and its current content? Other rows will be kept.',
'Delete row',
{ confirmButtonText: 'Delete', confirmButtonType: 'danger' }
)
if (!alive) return
if (version !== revision || data.value !== collection || !collection.includes(target)) {
HuiMessage.info('Row data changed. Deletion was cancelled; start again.')
return
}
data.value = collection.filter((item) => item !== target)
} catch {
// Cancelling or closing the dialog keeps every row.
} finally {
if (alive) removing.value = false
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="data" :columns="columns">
<template #name="{ row, rowIndex }">
<strong>{{ rowIndex + 1 }}. {{ row.name }}</strong>
</template>
<template #status="{ row }">
<HuiTag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
{{ row.status === 'active' ? 'Enabled' : 'Disabled' }}
</HuiTag>
</template>
<template #action="{ row }">
<HuiSpace :size="4">
<HuiButton
size="small"
type="primary"
variant="link"
@click.stop="HuiMessage.info(`Viewing ${row.name}`)"
>
View
</HuiButton>
<HuiButton
size="small"
type="danger"
variant="link"
:disabled="removing"
@click.stop="remove(row)"
>
Delete
</HuiButton>
</HuiSpace>
</template>
</HuiTable>
<HuiSpace wrap>
<HuiButton
size="small"
:disabled="data.length === source.length"
@click="data = source.slice()"
>
Restore deleted rows
</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
Summary and merged cells
show-summary sums numeric values from top-level rows. summaryMethod can supply each data column's summary. spanMethod returns [rowspan, colspan] or an object with those fields; a zero removes a covered cell.
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableSpanMethod, TableSummaryMethod } from '@nscode/handy-ui'
const data = [
{ id: 1, group: 'Group A', amount: 100 },
{ id: 2, group: 'Group A', amount: 80 }
]
const columns = [
{ prop: 'group', label: 'Group' },
{ prop: 'amount', label: 'Amount' }
]
const span: TableSpanMethod = ({ rowIndex, columnIndex }) =>
columnIndex === 0 ? (rowIndex === 0 ? [2, 1] : [0, 0]) : undefined
const summary: TableSummaryMethod = ({ data }) => [
'Total',
data.reduce((sum, row) => sum + Number(row.amount), 0)
]
</script>
<template>
<HuiTable
:data="data"
:columns="columns"
:span-method="span"
show-summary
:summary-method="summary"
border
/>
</template>
Mapping backend branch flags
Use an isLeaf getter to invert a backend hasChildren flag. A numeric key and the equivalent string remain separate rows.
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableLoadMethod, TableTreeProps } from '@nscode/handy-ui'
const data = [
{ id: 1, name: 'Branch', hasChildren: true },
{ id: '1', name: 'Leaf', hasChildren: false }
]
const treeProps: TableTreeProps = { isLeaf: (row) => !row.hasChildren }
const load: TableLoadMethod = async () => [{ id: 11, name: 'Child', hasChildren: false }]
</script>
<template>
<HuiTable
:data="data"
:columns="[{ prop: 'name', label: 'Name' }]"
:tree-props="treeProps"
:load="load"
selectable
/>
</template>
Form isolation
Table checkboxes are browsing controls: they do not inherit an outer Form disabled/readonly state, register its label, or trigger its validation. User cell, expand, empty, and loading slots retain their form context. Here the slot input stays disabled and receives the label association; checkbox size still follows Table.
<script setup lang="ts">
import { HuiForm, HuiFormItem, HuiInput, HuiTable } from '@nscode/handy-ui'
const boundaryData = [{ id: 1, name: 'Business value' }]
</script>
<template>
<HuiForm disabled size="large">
<HuiFormItem label="Business field">
<HuiTable
:data="boundaryData"
:columns="[{ prop: 'name', label: 'Name' }]"
selectable
size="small"
>
<template #name="{ row }"><HuiInput :model-value="row.name" /></template>
</HuiTable>
</HuiFormItem>
</HuiForm>
</template>
Virtual scrolling: navigate 10,000 rows
Navigate by a strict row key in the fixed-height window. Four alignments keep the target between the sticky header and summary. smooth uses native browser animation; true means the target was found and scrolling was requested, not that the animation finished. Select All still includes off-screen rows.
start aligns with the top of the body viewport, center centers the row, and end aligns with the bottom. The default nearest keeps a fully visible row in place and otherwise scrolls to the nearest edge. Targets near either end are clamped to the actual scroll range. Both rendering modes use these alignments and preserve horizontal scroll position.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableExpose, TableScrollToRowOptions } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const rows = Array.from({ length: 10000 }, (_, index) => ({
id: index + 1,
name: `Record ${index + 1}`,
amount: index + 1
}))
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 100 },
{ prop: 'name', label: 'Name', width: 200 },
{ prop: 'amount', label: 'Amount', width: 140, align: 'right' }
]
const selected = ref<(string | number)[]>([])
const smooth = ref(false)
const result = ref('No navigation yet')
const alignments = ['nearest', 'start', 'center', 'end'] as const
const locate = (
key: string | number,
align: NonNullable<TableScrollToRowOptions['align']> = 'nearest'
) => {
const found =
table.value?.scrollToRow(key, { align, behavior: smooth.value ? 'smooth' : 'auto' }) ?? false
result.value = `${String(key)} / ${align}: ${found ? 'Navigation requested' : 'Not found or viewport unavailable'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton v-for="align in alignments" :key="align" @click="locate(5000, align)"
>5000 / {{ align }}</HuiButton
>
<HuiButton @click="locate(10000, 'end')">Last row</HuiButton>
<HuiButton @click="locate('5000')">String '5000' (missing)</HuiButton>
</HuiSpace>
<HuiSpace
><span>smooth</span><HuiSwitch v-model="smooth" /><span>{{ result }}</span></HuiSpace
>
<span>10,000 rows; {{ selected.length }} selected</span>
<HuiTable
ref="table"
v-model:selected-keys="selected"
:data="rows"
:columns="columns"
:height="320"
:item-size="48"
virtual-scroll
selectable
stripe
show-summary
style="flex: none"
/>
</HuiSpace>
</template>
Virtual scrolling: fixed columns and summaries
Keep left/right fixed columns, sticky headers, and summaries in one native table. Toggle virtual scrolling to use the same scrollToRow method in ordinary mode. Navigation does not change selection or automatically reset sorting to the top. Explicit widths avoid auto layout changing with the rendered window.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableExpose } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const virtual = ref(true)
const result = ref('No navigation yet')
const rows = Array.from({ length: 200 }, (_, index) => ({
id: index + 1,
name: `Customer ${index + 1}`,
description: `Detailed description of record ${index + 1}`,
amount: index + 1
}))
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 100, fixed: 'left' },
{ prop: 'name', label: 'Name', width: 180 },
{ prop: 'description', label: 'Description', width: 600 },
{ prop: 'amount', label: 'Amount', width: 120, fixed: 'right', align: 'right' }
]
const locate = (key: number) => {
result.value = `${key}: ${table.value?.scrollToRow(key, { align: 'center' }) ?? false}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><span>virtualScroll</span><HuiSwitch v-model="virtual" /><HuiButton @click="locate(150)"
>Go to 150</HuiButton
><HuiButton @click="locate(1)">Go to 1</HuiButton><span>{{ result }}</span></HuiSpace
>
<div style="width: 600px; max-width: 100%; flex: none">
<HuiTable
ref="table"
:data="rows"
:columns="columns"
:height="300"
:item-size="48"
:virtual-scroll="virtual"
selectable
show-summary
border
/>
</div>
</HuiSpace>
</template>
Virtual scrolling: trees and collapsed targets
The virtual window follows the expanded logical tree rows. scrollToRow does not expand ancestors: a collapsed descendant returns false; expand first to navigate to it. Select All still includes every loaded node, and collapsing branches preserves selection.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableExpose } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const result = ref('No navigation yet')
const rows = Array.from({ length: 50 }, (_, group) => ({
id: `group-${group}`,
name: `Group ${group + 1}`,
children: Array.from({ length: 200 }, (_, child) => ({
id: `group-${group}-${child}`,
name: `Node ${group + 1}-${child + 1}`
}))
}))
const columns: TableColumnConfig[] = [{ prop: 'name', label: 'Node', width: 400 }]
const locate = () => {
result.value = `group-30-100: ${table.value?.scrollToRow('group-30-100', { align: 'center' }) ?? false}`
}
const expand = () => {
table.value?.expandAll()
result.value = 'Expanded all groups'
}
const collapse = () => {
table.value?.collapseAll()
result.value = 'Collapsed all groups'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><HuiButton @click="locate">Go to descendant</HuiButton
><HuiButton @click="expand">Expand all first</HuiButton
><HuiButton @click="collapse">Collapse all</HuiButton><span>{{ result }}</span></HuiSpace
>
<HuiTable
ref="table"
:data="rows"
:columns="columns"
:max-height="320"
:item-size="48"
virtual-scroll
selectable
stripe
style="flex: none"
/>
</HuiSpace>
</template>
Virtual-scroll limits
- virtualScroll requires a valid height or maxHeight. Percentage heights need a parent with a definite height. Without a usable constraint the table stays fully rendered and emits a development warning.
- itemSize is a finite positive fixed pixel height, not a callback. Omitted or invalid values measure the first real data row in layout coordinates after mounting. Hidden zero-sized rows do not replace a valid measurement. Changing size, border, or itemSize resets that measurement.
- Data cells stay on one line. Content taller than the fixed row box is clipped; off-screen slot components unmount, so store editable state in application data.
- Detail expansion is unavailable: the detail column and expand slot are suppressed with a development warning. Tree expansion remains supported.
- rowspan greater than 1 becomes 1. Vertically covered cells are restored independently; horizontal colspan and same-row covered cells stay merged. A development warning describes this degradation.
- auto layout remains auto and can change width as the window changes. This combination warns in development; explicit column widths are recommended for stable fixed offsets.
- Each active unsupported combination warns once. Ordinary parent rerenders and scrolling do not repeat it. Leaving and re-entering the combination starts a new warning session.
- Native table semantics, sticky headers, summaries, and full-data selection remain. ARIA indices include logical rows, headers, and the summary.
- scrollToRow uses strict key types; 1 and '1' differ. Missing rows, descendants of collapsed nodes, an unusable viewport, SSR, and calls after unmount return false. It never expands ancestors, changes selection, or focuses a cell. Smooth scrolling is native and completion is not represented by the boolean return value.
Header filters
Set filterOptions on a column to show its filter button. Multiple selection edits a draft and requires confirmation; filterMultiple: false applies immediately. Closing or Escape discards the draft. External filter, column identity or option changes invalidate old sessions and callbacks.
filterMethod(value, row, column, cellValue) performs local matching; its fourth argument uses the shared path/accessor value. Values within one column use OR, columns use AND. Omit the method for remote filtering. filterValue uses internal state when omitted and is controlled by prop presence, including undefined. Rejected updates retain the actual results. update:filterValue precedes filter-change, each with a separate snapshot.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTable, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { TableColumnConfig, TableExpose, TableFilterValue } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const filters = ref<TableFilterValue>({})
const status = ref('No filters')
const rows = [
{ id: 1, name: 'Alex', state: { code: 'active' }, amount: 30 },
{ id: 2, name: 'Robin', state: { code: 'paused' }, amount: 50 },
{ id: 3, name: 'Sam', state: { code: 'active' }, amount: 70 }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name' },
{
prop: 'state.code',
label: 'Status (multiple)',
filterOptions: [
{ label: 'Active', value: 'active' },
{ label: 'Paused', value: 'paused' }
],
filterMethod: (value, _row, _column, cellValue) => value === cellValue
},
{
prop: 'amount',
label: 'Amount (single)',
sortable: true,
filterMultiple: false,
filterOptions: [
{ label: 'At least 50', value: 50 },
{ label: 'At least 70', value: 70 }
],
filterMethod: (value, _row, _column, cellValue) => Number(cellValue) >= Number(value)
}
]
const onFilter = (value: TableFilterValue) => {
status.value = JSON.stringify(value)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="table?.clearFilter(['state.code'])">Reset status</HuiButton>
<HuiButton @click="table?.clearFilter()">Reset all</HuiButton>
</HuiSpace>
<span>{{ status }}</span>
<HuiTable
ref="table"
v-model:filter-value="filters"
:data="rows"
:columns="columns"
selectable
show-summary
@filter-change="onFilter"
/>
</HuiSpace>
</template>
Summary methods receive filtered root rows; sorting and span indexes follow the filtered order. Hidden selected/current keys are retained; Select All only affects filtered logical rows. Trees filter roots by default. filterChildren: true filters descendants and preserves ancestors with matching descendants without mutating the original tree. Unloaded descendants do not participate.
Remote filters and custom panels
Omit filterMethod to pass conditions to remote queries. This example simulates a server response using a local array. The filter-<prop> slot receives value/setValue/confirm/reset/close: value is a draft, reset clears and applies the column, close discards it. Callbacks belong to their open session and do nothing after reopening or unmounting.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTable, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { TableFilterValue } from '@nscode/handy-ui'
const source = [
{ id: 1, name: 'Alex', status: 'open' },
{ id: 2, name: 'Robin', status: 'closed' }
]
const rows = ref(source)
const filters = ref<TableFilterValue>({})
const requests = ref(0)
const columns = [
{ prop: 'name', label: 'Name' },
{ prop: 'status', label: 'Remote status', filterOptions: [] }
]
const query = (value: TableFilterValue) => {
requests.value++
const selected = value.status ?? []
rows.value = selected.length ? source.filter((row) => selected.includes(row.status)) : source
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<span>Requests: {{ requests }}</span>
<HuiTable v-model:filter-value="filters" :data="rows" :columns="columns" @filter-change="query">
<template #filter-status="{ value, setValue, confirm, reset, close }">
<HuiSpace direction="vertical" fill>
<span>Draft: {{ value.join(', ') || 'none' }}</span>
<HuiButton @click="setValue(['open'])">Open only</HuiButton>
<HuiSpace>
<HuiButton type="primary" @click="confirm">Apply</HuiButton>
<HuiButton @click="reset">Reset</HuiButton>
<HuiButton @click="close">Cancel</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
</HuiTable>
</HuiSpace>
</template>
Selection and sorting ownership
Omitting selectedKeys or sortState keeps internal state; listening for updates alone does not control either. Passing a prop, including undefined, makes it controlled: undefined means empty selection or no sorting, even with defaultSort. Parent values decide the display; rejected requests never overwrite the internal draft. Removing a prop restores its previous internal value. Changes in control mode produce a development warning. Same-tick selection requests still accumulate; after that tick a rejected request falls back to the parent value. Data cleanup only requests update:selectedKeys and does not emit a user selection-change.
Current row and controlled requests
Enable highlight-current to track clicks by row-key. Current-row state is independent of selectedKeys: clicking a row does not check it, and selection or expansion controls do not change the current row. A leading accent and aria-current distinguish the current row.
Omit current-key for internal state. Passing it, including explicit undefined, makes it controlled; null clears it. A rejected update keeps the parent's highlight. Clicks and setCurrentRow(row) emit update:currentKey followed by current-change(key, { row, previousKey, previousRow }). Choosing the actual current key again emits neither. Context describes the request even when the parent immediately normalizes it.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTable, HuiButton, HuiSwitch, HuiSpace } from '@nscode/handy-ui'
import type { TableExpose, TableCurrentChangeContext } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const currentKey = ref<string | number | null>(null)
const selectedKeys = ref<(string | number)[]>([])
const acceptRequest = ref(true)
const status = ref('Click a row to observe a request')
const rows = [
{ id: 0, name: 'Alex' },
{ id: 2, name: 'Robin' }
]
const columns = [{ prop: 'name', label: 'Name' }]
const updateCurrent = (key: string | number | null) => {
if (acceptRequest.value) currentKey.value = key
}
const onCurrent = (key: string | number | null, context: TableCurrentChangeContext) => {
status.value = `Requested ${key ?? 'none'}, previous ${context.previousRow?.name ?? 'none'}, row ${context.row?.name ?? 'none'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch
v-model="acceptRequest"
active-text="Accept updates"
inactive-text="Reject updates"
/>
<HuiButton @click="table?.setCurrentRow(rows[1])">Set second row</HuiButton>
<HuiButton @click="table?.setCurrentRow(null)">Clear current row</HuiButton>
<HuiButton @click="currentKey = 0">Set first key externally</HuiButton>
</HuiSpace>
<span
>Actual key: {{ currentKey ?? 'none' }}; selected:
{{ selectedKeys.join(', ') || 'none' }}</span
>
<span>{{ status }}</span>
<HuiTable
ref="table"
v-model:selected-keys="selectedKeys"
:data="rows"
:columns="columns"
:current-key="currentKey"
highlight-current
selectable
@update:current-key="updateCurrent"
@current-change="onCurrent"
/>
</HuiSpace>
</template>
Same-key replacements and reordering preserve the current row. Collapsing a tree branch retains its child key. Removing the key from data only requests update:currentKey(null) without a user current-change. The parent still decides in controlled mode. setCurrentRow accepts a same-key copy but uses the actual data row in context; unknown keys do nothing. Omit its argument or pass null to clear. Highlighting does not scroll; use scrollToRow(key) when needed.
Editing and validating detail rows
Compose inputs, numbers, selects and EditableText in cell slots with an outer Form. Resolve field paths from a stable row id and the original model index; sorted or filtered rowIndex values are display indexes. Saving stores a local independent snapshot. Removal requires confirmation, cancellation keeps input, and a changed collection invalidates an old confirmation. Read-only mode blocks all write actions. The table does not own an editing engine.
<script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import {
HuiButton,
HuiEditableText,
HuiForm,
HuiFormItem,
HuiInput,
HuiInputNumber,
HuiMessageBox,
HuiSelect,
HuiSpace,
HuiSwitch,
HuiTable
} from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
interface Detail {
id: number
name: string
unit: string
quantity: number | null
price: number | null
note: string
}
const form = ref<InstanceType<typeof HuiForm>>()
const readonly = ref(false)
const saving = ref(false)
const removing = ref<number | null>(null)
const status = ref('Sort before editing; saving validates all details')
const saved = ref<Detail[]>([])
let nextId = 3
let alive = true
onBeforeUnmount(() => {
alive = false
})
const model = reactive<{ rows: Detail[] }>({
rows: [
{ id: 1, name: 'Notebook', unit: '本', quantity: 2, price: 6, note: '' },
{ id: 2, name: 'Pen', unit: '支', quantity: 3, price: 2, note: '' }
]
})
let removalRevision = 0
watch([() => model.rows, readonly, saving], () => removalRevision++, {
deep: true,
flush: 'sync'
})
const units = [
{ label: 'Book', value: '本' },
{ label: 'Piece', value: '支' },
{ label: 'Box', value: '盒' }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: 'Item name', width: 180, sortable: true },
{ prop: 'unit', label: 'Unit', width: 100 },
{ prop: 'quantity', label: 'Quantity', width: 160, sortable: true },
{ prop: 'price', label: 'Price', width: 160 },
{
prop: 'amount',
label: 'Amount',
width: 100,
accessor: (row) => Number(row.quantity ?? 0) * Number(row.price ?? 0),
formatter: (_row, _column, value) => Number(value).toFixed(2)
},
{ prop: 'note', label: 'Note', width: 200 },
{ prop: 'actions', label: 'Actions', width: 90 }
]
const total = computed(() =>
model.rows
.reduce((sum, row) => sum + Number(row.quantity ?? 0) * Number(row.price ?? 0), 0)
.toFixed(2)
)
// Validation uses model indexes; rowIndex only describes the displayed order.
const pathFor = (id: number, field: keyof Detail) =>
`rows.${model.rows.findIndex((row) => row.id === id)}.${field}`
const add = () => {
if (readonly.value || saving.value || removing.value !== null) return
model.rows.push({ id: nextId++, name: '', unit: '本', quantity: 1, price: 0, note: '' })
status.value = 'Added a detail to fill in'
}
const remove = async (row: Detail) => {
if (readonly.value || saving.value || removing.value !== null || !model.rows.includes(row))
return
const collection = model.rows
const snapshot = collection.slice()
const version = removalRevision
removing.value = row.id
try {
await HuiMessageBox.confirm(
`Remove detail “${row.name || 'Unnamed item'}” and its current input? Other details are unaffected.`,
'Remove detail',
{
confirmButtonText: 'Remove',
confirmButtonType: 'danger'
}
)
if (!alive) return
if (
readonly.value ||
saving.value ||
version !== removalRevision ||
model.rows !== collection ||
snapshot.length !== collection.length ||
snapshot.some((item, index) => item !== collection[index])
) {
status.value = 'Details changed; removal cancelled. Try again'
return
}
const index = collection.indexOf(row)
if (index < 0) return
collection.splice(index, 1)
status.value = 'Removed the detail'
} catch (action) {
if (alive)
status.value =
action === 'cancel' || action === 'close'
? 'Removal cancelled; detail retained'
: 'Removal failed; detail retained'
} finally {
if (alive) removing.value = null
}
}
const save = async () => {
if (readonly.value || saving.value || removing.value !== null) return
if (!model.rows.length) {
status.value = 'Add at least one detail'
return
}
const collection = model.rows
const snapshot = collection.slice()
saving.value = true
try {
const result = await form.value?.validate()
if (!alive) return
if (
readonly.value ||
model.rows !== collection ||
snapshot.length !== collection.length ||
snapshot.some((item, index) => item !== collection[index])
) {
status.value = 'Details changed; save again'
return
}
if (!result?.valid) {
status.value = 'Correct highlighted details before saving'
return
}
saved.value = collection.map((row) => ({ ...row }))
status.value = `Validated and saved ${saved.value.length} detail snapshots`
} finally {
if (alive) saving.value = false
}
}
</script>
<template>
<HuiSpace class="table-detail-editor" direction="vertical" fill>
<HuiSpace wrap>
<HuiButton class="detail-add" :disabled="readonly || saving || removing !== null" @click="add"
>Add detail</HuiButton
>
<HuiButton
class="detail-save"
type="primary"
:loading="saving"
:disabled="readonly || removing !== null"
@click="save"
>Validate and save</HuiButton
>
<HuiSwitch v-model="readonly" active-text="Read only" />
<span>Total: {{ total }}</span>
</HuiSpace>
<HuiForm
ref="form"
:model="model"
:label-width="0"
:readonly="readonly || saving"
style="overflow-x: auto"
@submit.prevent="save"
>
<HuiTable
:data="model.rows"
:columns="columns"
row-key="id"
:default-sort="{ prop: 'name', order: 'ascending' }"
style="min-width: 1100px"
>
<template #name="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'name')"
:rules="[{ required: true, message: 'Enter an item name' }]"
>
<HuiInput v-model="row.name" :aria-label="`Item name-${row.id}`" />
</HuiFormItem>
</template>
<template #unit="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'unit')"
:rules="[{ required: true, message: 'Select a unit' }]"
>
<HuiSelect v-model="row.unit" :options="units" :aria-label="`Unit-${row.id}`" />
</HuiFormItem>
</template>
<template #quantity="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'quantity')"
:rules="[
{ required: true, type: 'number', min: 1, message: 'Quantity must be at least 1' }
]"
>
<HuiInputNumber v-model="row.quantity" :min="1" :aria-label="`Quantity-${row.id}`" />
</HuiFormItem>
</template>
<template #price="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'price')"
:rules="[
{
required: true,
type: 'number',
min: 0,
message: 'Price is required and must be nonnegative'
}
]"
>
<HuiInputNumber
v-model="row.price"
:min="0"
:precision="2"
:aria-label="`Price-${row.id}`"
/>
</HuiFormItem>
</template>
<template #note="{ row }">
<HuiEditableText
v-model="row.note"
trigger="click"
show-actions
empty-text="Click to edit note"
:disabled="readonly || saving"
/>
</template>
<template #actions="{ row }">
<HuiButton
type="danger"
variant="text"
:aria-label="`Remove detail-${row.id}`"
:disabled="readonly || saving || removing !== null"
@click="remove(row)"
>Remove</HuiButton
>
</template>
</HuiTable>
</HuiForm>
<span class="detail-status" role="status">{{ status }}</span>
<code class="detail-saved">Saved snapshot: {{ JSON.stringify(saved) }}</code>
</HuiSpace>
</template>
Lazy loading errors and retry
A thrown error or rejected Promise emits load-error with the original row, the strictly typed key, and the original error. The row stays collapsed and its loading state is released. Retry with the expand arrow or toggleRowExpansion(row, true). This example fails once, then succeeds, with visible feedback and a request count.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type {
TableColumnConfig,
TableExpose,
TableLoadErrorContext,
TableLoadMethod
} from '@nscode/handy-ui'
const table = ref<TableExpose>()
const data = [{ id: 1, name: 'Directory to load', isLeaf: false }]
const columns: TableColumnConfig[] = [{ prop: 'name', label: 'Name' }]
const attempts = ref(0)
const errorText = ref('')
const status = ref('Expand the directory. The first request will fail.')
const load: TableLoadMethod = async () => {
errorText.value = ''
attempts.value += 1
if (attempts.value === 1) throw new Error('Simulated connection failure')
status.value = 'Retry succeeded. The child row is expanded.'
return [{ id: 2, name: 'File loaded after retry', isLeaf: true }]
}
const handleLoadError = ({ row, key, error }: TableLoadErrorContext) => {
errorText.value = error instanceof Error ? error.message : String(error)
status.value = `${row.name} (key=${key}) failed: ${errorText.value}. Use the arrow or the button to retry.`
}
const retry = () => table.value?.toggleRowExpansion(data[0], true)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable
ref="table"
:data="data"
:columns="columns"
:load="load"
@load-error="handleLoadError"
/>
<HuiButton class="load-retry" :disabled="!errorText" @click="retry"
>Retry directory loading</HuiButton
>
<span class="load-status" role="status">{{ status }} Requests: {{ attempts }}</span>
</HuiSpace>
</template>
Disabled rows and single selection
Use rowSelectable(row) to control row selection. Clicks, Select All and toggleRowSelection all honor it. Previously selected rows remain selected if they become disabled. Header state and Select All count all eligible logical rows after filtering, including collapsed children and rows outside a virtual window. clearSelection() still clears the entire selection.
When selectable is enabled, selectionMode="single" renders one native radio group without Select All. Clicking the selected item does not uncheck it. Pass false to the row method or call clearSelection() to clear. If an external array contains several keys, only the first is effective and a cleanup update is requested; the parent retains control. Current-row highlighting remains independent.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableExpose, TableRowData } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const mode = ref<'multiple' | 'single'>('multiple')
const accept = ref(true)
const lockSecond = ref(false)
const keys = ref<(string | number)[]>([])
const requests = ref(0)
const message = ref(
'The system account cannot be selected. Switch between single and multiple selection.'
)
const data = [
{ id: 0, name: 'System account', locked: true },
{ id: 1, name: 'Account A', locked: false },
{ id: 2, name: 'Account B', locked: false }
]
const columns: TableColumnConfig[] = [{ prop: 'name', label: 'Account' }]
const rowSelectable = (row: TableRowData) => !row.locked && !(row.id === 2 && lockSecond.value)
const update = (next: (string | number)[]) => {
requests.value += 1
message.value = `Requested keys: ${JSON.stringify(next)}; parent ${accept.value ? 'accepts' : 'rejects'}.`
if (accept.value) keys.value = next.slice()
}
const selectSystem = () => {
const before = requests.value
table.value?.toggleRowSelection(data[0], true)
if (requests.value === before)
message.value = 'The system account is disabled. The public method sent no update.'
}
</script>
<template>
<HuiSpace class="table-selection-demo" direction="vertical" fill>
<HuiSpace wrap>
<HuiButton class="selection-multiple" @click="mode = 'multiple'">Multiple</HuiButton>
<HuiButton class="selection-single" @click="mode = 'single'">Single</HuiButton>
<HuiSwitch v-model="accept" active-text="Accept requests" inactive-text="Reject requests" />
<HuiSwitch v-model="lockSecond" active-text="Disable account B" />
</HuiSpace>
<HuiSpace wrap>
<HuiButton class="selection-system" @click="selectSystem"
>Try selecting the system account</HuiButton
>
<HuiButton :disabled="mode === 'single'" @click="table?.toggleAllSelection()"
>Toggle all eligible rows</HuiButton
>
<HuiButton @click="table?.clearSelection()">Clear selection</HuiButton>
<HuiButton @click="keys = [0]">Set the system account externally</HuiButton>
</HuiSpace>
<HuiTable
ref="table"
:data="data"
:columns="columns"
selectable
:selection-mode="mode"
:row-selectable="rowSelectable"
:selected-keys="keys"
@update:selected-keys="update"
/>
<span class="selection-status" role="status">{{ message }}</span>
<span class="selection-actual"
>Mode: {{ mode }}; parent keys: {{ JSON.stringify(keys) }}; effective selection:
{{ table?.selection.map((row) => row.name).join('、') || 'None' }}; requests:
{{ requests }}</span
>
</HuiSpace>
</template>
Automatic Layout and Theme Spacing
Header, body, and summary content boxes use the same width calculation: the column constraint minus horizontal padding for the current size and any right border. Large/default/small still use --hui-spacing-4/3/2; border width still uses --hui-border-width. The last column has no right border and does not subtract one.
This example sets theme spacing to 24/20/12px and borders to 2px on an ancestor. Switching size or borders updates content boxes while long text keeps single-line ellipsis. Automatic column constraints and the table's minimum container width keep their existing behavior.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiTable, HuiSpace } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const variableSize = ref<'large' | 'default' | 'small'>('default')
const variableBorder = ref(true)
const variableRows = [
{ id: 1, name: 'A long name for verifying the content width and truncation', amount: 120 },
{ id: 2, name: 'Another long name for checking alignment', amount: 240 }
]
const variableColumns: TableColumnConfig[] = [
{ prop: 'name', label: 'Name (180px)', width: 180 },
{ prop: 'amount', label: 'Amount (160px)', width: 160 }
]
</script>
<template>
<div
class="table-variables-demo"
style="--hui-spacing-2:12px;--hui-spacing-3:20px;--hui-spacing-4:24px;--hui-border-width:2px;display:flex;flex-direction:column;gap:var(--hui-spacing-4);max-width:600px"
>
<HuiSpace wrap>
<HuiButton
class="table-variables-large"
:type="variableSize === 'large' ? 'primary' : 'default'"
@click="variableSize = 'large'"
>large</HuiButton
>
<HuiButton
class="table-variables-default"
:type="variableSize === 'default' ? 'primary' : 'default'"
@click="variableSize = 'default'"
>default</HuiButton
>
<HuiButton
class="table-variables-small"
:type="variableSize === 'small' ? 'primary' : 'default'"
@click="variableSize = 'small'"
>small</HuiButton
>
<HuiButton class="table-variables-border" @click="variableBorder = !variableBorder"
>Border: {{ variableBorder ? 'On' : 'Off' }}</HuiButton
>
</HuiSpace>
<p class="table-variables-result">
Current size: {{ variableSize }};Border: {{ variableBorder ? 'On' : 'Off' }}
</p>
<HuiTable
:data="variableRows"
:columns="variableColumns"
:size="variableSize"
:border="variableBorder"
table-layout="auto"
show-summary
/>
</div>
</template>
The former --hui-table-auto-cell-padding and --hui-table-auto-cell-border names represent internal width calculations. They are now private variables without old-name fallbacks. Use size, border props, and theme variables to configure the actual appearance. Each auto table resets its own intermediate values; nested tables keep their own layout and size.
Fill Remaining Viewport Height
Enable fillViewport to use the space from the table's top edge to the layout viewport bottom. fillOffset reserves a bottom gap; fillMinHeight defaults to 200px and includes the header and summary. Fill ignores height; maxHeight remains an independent upper limit, even below the minimum. Disable fill to restore height.
Window resize and body/target size notifications are batched into one frame. For a position-only change without a size notification, call updateLayout(). SSR leaves the viewport height unset and keeps maxHeight. Virtual scrolling also accepts fillViewport as its height constraint.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableExpose } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const fill = ref(false)
const expanded = ref(false)
const offset = ref(24)
const minimum = ref(200)
const result = ref('Not refreshed manually')
const rows = Array.from({ length: 80 }, (_, id) => ({ id, name: `Record ${id + 1}` }))
const columns = [{ prop: 'name', label: 'Name' }]
const refresh = () => {
table.value?.updateLayout()
result.value = 'Layout refreshed at the current position'
}
</script>
<template>
<HuiSpace direction="vertical" fill class="table-fill-demo">
<HuiSpace wrap>
<HuiSwitch
v-model="fill"
class="table-fill-toggle"
active-text="Fill on"
inactive-text="Fill off"
/>
<HuiButton class="table-fill-query" @click="expanded = !expanded"
>Toggle filters above</HuiButton
>
<HuiButton class="table-fill-offset" @click="offset = offset === 24 ? 80 : 24"
>Bottom gap: {{ offset }}px</HuiButton
>
<HuiButton class="table-fill-min" @click="minimum = minimum === 200 ? 300 : 200"
>Minimum: {{ minimum }}px</HuiButton
>
<HuiButton class="table-fill-refresh" @click="refresh">updateLayout()</HuiButton>
</HuiSpace>
<p v-if="expanded">
Expanding the filter area moves the table. Window or page size notifications update the
available height; use the method for position-only changes.
</p>
<p class="table-fill-result">
{{ result }}. Turning fill off restores 240px; the 480px maximum remains active.
</p>
<HuiTable
ref="table"
:data="rows"
:columns="columns"
:fill-viewport="fill"
:fill-offset="offset"
:fill-min-height="minimum"
:height="240"
:max-height="480"
border
style="flex: none"
/>
</HuiSpace>
</template>
Reuse the Height Tool or a Definite Parent Height
useFillHeight(target, { offset, minHeight, enabled }) returns readonly height and an immediate update(). The target accepts a ref/getter; options accept values, refs or getters. Defaults are 0/200/true. No target, disabled or SSR produces undefined; disabling or unmounting removes subscriptions. Non-finite numbers use defaults, negative minimums become zero, and negative offsets deliberately extend the area. Returned height is the target's total outer-box height, not a body-only value; use box-sizing: border-box when adding borders or padding.
A definite flex parent can use height="100%" directly. The two approaches are shown separately:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable, useFillHeight } from '@nscode/handy-ui'
const target = ref<HTMLElement>()
const { height, update } = useFillHeight(target, { offset: 24, minHeight: 200 })
const rows = Array.from({ length: 40 }, (_, id) => ({ id, name: `Record ${id + 1}` }))
const columns = [{ prop: 'name', label: 'Name' }]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="update">Refresh container height</HuiButton>
<div
ref="target"
:style="{
height: height === undefined ? undefined : `${height}px`,
maxHeight: '360px',
overflow: 'auto'
}"
>
<p v-for="line in 30" :key="line">Scrollable content, line {{ line }}</p>
</div>
<div style="display:flex;flex-direction:column;height:240px">
<p style="flex:none">With a definite parent height, the table can use height="100%".</p>
<HuiTable :data="rows" :columns="columns" height="100%" style="min-height:0" />
</div>
</HuiSpace>
</template>
Disabled rows
Use rowSelectable(row) to control row selection. Clicks, Select All and toggleRowSelection all honor it. Previously selected rows remain selected if they become disabled. Header state and Select All count all eligible logical rows in the current data, including collapsed children and rows outside a virtual window. clearSelection() still clears the entire selection.
Public row methods check the current row with the same key, so an old copy cannot bypass the restriction. Rejected parent updates retain the actual selection. Availability changes apply to the next operation.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableExpose, TableRowData } from '@nscode/handy-ui'
const table = ref<TableExpose>()
const accept = ref(true)
const lockSecond = ref(false)
const keys = ref<(string | number)[]>([])
const requests = ref(0)
const message = ref(
'The system account cannot be selected. Toggle parent acceptance and row availability.'
)
const data = [
{ id: 0, name: 'System account', locked: true },
{ id: 1, name: 'Account A', locked: false },
{ id: 2, name: 'Account B', locked: false }
]
const columns: TableColumnConfig[] = [{ prop: 'name', label: 'Account' }]
const rowSelectable = (row: TableRowData) => !row.locked && !(row.id === 2 && lockSecond.value)
const update = (next: (string | number)[]) => {
requests.value += 1
message.value = `Requested keys: ${JSON.stringify(next)}; parent ${accept.value ? 'accepts' : 'rejects'}.`
if (accept.value) keys.value = next.slice()
}
const selectSystem = () => {
const before = requests.value
table.value?.toggleRowSelection(data[0], true)
if (requests.value === before)
message.value = 'The system account is disabled. The public method sent no update.'
}
</script>
<template>
<HuiSpace class="table-selection-demo" direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="accept" active-text="Accept requests" inactive-text="Reject requests" />
<HuiSwitch v-model="lockSecond" active-text="Disable account B" />
</HuiSpace>
<HuiSpace wrap>
<HuiButton class="selection-system" @click="selectSystem"
>Try selecting the system account</HuiButton
>
<HuiButton @click="table?.toggleAllSelection()">Toggle all eligible rows</HuiButton>
<HuiButton @click="table?.clearSelection()">Clear selection</HuiButton>
<HuiButton @click="keys = [0]">Set the system account externally</HuiButton>
</HuiSpace>
<HuiTable
ref="table"
:data="data"
:columns="columns"
selectable
:row-selectable="rowSelectable"
:selected-keys="keys"
@update:selected-keys="update"
/>
<span class="selection-status" role="status">{{ message }}</span>
<span class="selection-actual"
>Parent keys: {{ JSON.stringify(keys) }}; effective selection:
{{ table?.selection.map((row) => row.name).join('、') || 'None' }}; requests:
{{ requests }}</span
>
</HuiSpace>
</template>
Performance
For large datasets, define columns in setup rather than creating column configurations inline in the template. The table reuses unchanged sort and filter specifications, parsed property paths, and string collators for the current language. Local sorting reads each row's value once before comparing rows.
An inline rowKey function does not rebuild the row index merely because its reference changes on a parent render. When changing the function's key derivation algorithm, also change the table's key to rebuild row identities and selection state.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| data | TableRowData[] | [] | Row data |
| columns | TableColumnConfig[] | — | Columns; inferred from the first row when omitted or empty |
| tableLayout | TableLayout | 'fixed' | Fixed configured widths or automatic single-line content widths with per-column maximums |
| stripe | boolean | false | Alternating row backgrounds |
| border | boolean | false | Outer border, cell dividers and header resize controls |
| size | 'large' | 'default' | 'small' | ConfigProvider or default | Control density |
| height | number | string | — | Fixed height; numbers are pixels; headers remain visible when scrolling |
| maxHeight | number | string | — | Maximum height before scrolling |
| fillViewport | boolean | false | Fill to the layout viewport bottom; ignores height, keeps maxHeight |
| fillOffset | number | 0 | Bottom gap in px |
| fillMinHeight | number | 200 | Minimum total fill height in px, still constrained by maxHeight |
| virtualScroll | boolean | false | Render a fixed-height window; requires height, maxHeight or fillViewport. |
| itemSize | number | Measured first data row | Fixed row height in pixels; a positive finite number. Omitted or invalid values use measurement. |
| rowKey | string | ((row: TableRowData) => string | number) | 'id' | Stable unique row identifier; numeric callbacks preserve numbers |
| highlightCurrent | boolean | false | Track row clicks and show current-row highlight, independent of selection |
| currentKey / v-model:current-key | string | number | null | Internal null | Controlled by prop presence, including undefined; null clears |
| filterValue / v-model:filter-value | TableFilterValue | Internal {} | Per-column values; controlled by prop presence, including undefined |
| emptyText | string | Locale No data | Text when empty and not loading |
| selectable | boolean | false | Checkbox selection column |
| rowSelectable | (row: TableRowData) => boolean | — | false disables row clicks, Select All and toggleRowSelection; existing selected rows are preserved |
| selectionMode | 'multiple' | 'single' | 'multiple' | Effective when selectable; single renders radio buttons without Select All |
| selectedKeys / v-model:selected-keys | (string | number)[] | Internal empty array | Controlled by prop presence (undefined means empty); omit for internal state |
| reserveSelection | boolean | false | Preserve selected keys and known rows across pages; requires stable unique rowKey values |
| defaultSort | { prop: string; order: 'ascending' | 'descending' } | — | Initial sorting, read once |
| sortState / v-model:sort-state | TableSortState | — | Controlled sorting, taking precedence over defaultSort; update the prop to apply requests |
| showHeader | boolean | true | Render the table header |
| rowClassName | string | ((row: TableRowData, rowIndex: number) => string) | — | Row class |
| cellClassName | string | ((row: TableRowData, column: TableColumnConfig, rowIndex: number) => string) | — | Body cell class |
| headerCellClassName | string | ((column: TableColumnConfig) => string) | — | Header cell class |
| treeProps | TableTreeProps | children / isLeaf | Tree field mapping |
| indent | number | 16 | Indentation per tree depth in pixels |
| load | TableLoadMethod | — | Lazy child-row loading |
| defaultExpandAll | boolean | false | Initially expand all available rows |
| defaultExpandedKeys | (string | number)[] | — | Initially expanded row keys |
| expandable | boolean | false | Separate expansion column for the expand slot |
| accordion | boolean | false | Only one expandable detail row open at a time |
| showSummary | boolean | false | Display a summary row |
| summaryText | string | Locale Total | First summary-column text |
| summaryMethod | TableSummaryMethod | — | Custom summary data |
| spanMethod | TableSpanMethod | — | Cell row and column spans |
| showOverflowTooltip | boolean | false | Single-line overflowing body cells with hover tooltips |
| loading | boolean | false | Mask only the visible body; hide empty content while loading |
| loadingText | string | Locale Loading | Spinner text; empty string hides text |
Column configuration
| Property | Type | Default | Description |
|---|---|---|---|
| prop | string | Required | Field or nested path; a matching literal key takes precedence. Also the column and slot identity |
| accessor | (row: TableRowData) => unknown | — | Raw value getter, before prop; shared by display, formatter, default sorting and summaries |
| filterOptions | TableFilterOption[] | — | Show the filter button; an empty list can use a custom filter slot |
| filterMultiple | boolean | true | Multiple draft with confirmation; false applies a single value immediately |
| filterMethod | (value, row, column, cellValue) => boolean | — | Local matching using shared raw values; omit for remote filtering |
| filterChildren | boolean | false | Recursively filter descendants and retain matching ancestors |
| label | string | Required | Header label |
| width | number | string | — | Column width; numbers are pixels |
| align | 'left' | 'center' | 'right' | left, or center for groups | Cell and header alignment |
| sortable | boolean | 'custom' | false | Local sorting or event-only remote sorting |
| sortMethod | (a: TableRowData, b: TableRowData, order: TableSortOrder) => number | — | Local comparator for sortable:true; descending results are reversed by the table |
| sortOrders | TableSortOrder[] | ['ascending', 'descending', null] | Header sort cycle; one entry fixes the order; an empty array uses the default |
| fixed | 'left' | 'right' | — | Sticky column side; provide width |
| className | string | — | Header and body cell class |
| formatter | (row: TableRowData, column: TableColumnConfig, value: unknown) => string | — | Text formatter; cell slots take precedence |
| children | TableColumnConfig[] | — | Nested header columns |
| resizable | boolean | true | Allow resizing when border is enabled |
| minWidth | number | Resize default 40 | Minimum resized width; also a minimum in auto layout without an explicit width |
| maxWidth | number | string | — | Auto content maximum; explicit or resized width takes precedence; spare cell space is possible |
| showOverflowTooltip | boolean | Table setting | Per-column overflow behavior |
Events
| Event | Parameters | Description |
|---|---|---|
| select | (selection: TableRowData[], row: TableRowData) | A row checkbox changed |
| select-all | (selection: TableRowData[]) | Header checkbox changed |
| update:selectedKeys | (keys: (string | number)[]) | Request new keys from a selection action or data cleanup |
| update:currentKey | (key: string | number | null) | Requests current key; missing data keys only emit this update |
| update:filterValue | (value: TableFilterValue) | Requests new filters; parent decides in controlled mode |
| filter-change | (value: TableFilterValue) | Confirm/reset/clear request, after update; independent snapshot |
| current-change | (key: string | number | null, context: TableCurrentChangeContext) | User or explicit method request; follows update, context includes row/previousKey/previousRow |
| selection-change | (selection: TableRowData[]) | Proposed selected rows after a selection action, even if refused; data cleanup only requests update:selectedKeys |
| update:sortState | (sort: TableSortState) | Request a sorting update from header interaction or sort()/clearSort() |
| sort-change | (sort: TableSortState) | User changed header sorting; methods and external assignments do not emit this event |
| row-click | (row, column, event: MouseEvent) | A data cell was clicked |
| row-dblclick | (row, column, event: MouseEvent) | A data cell was double-clicked |
| row-contextmenu | (row, column, event: MouseEvent) | A data cell received contextmenu; default behavior remains intact |
| cell-click | (row, column, cell: HTMLTableCellElement, event: MouseEvent) | A data cell was clicked |
| column-resize | (column: TableColumnConfig, width: number, previous: number) | A column was resized by pointer or keyboard |
| expand-change | (row, expanded: boolean, expandedRows: TableRowData[]) | A tree or detail row changed expansion state |
| load-error | (context: TableLoadErrorContext) | Current lazy loading threw or rejected; includes row, key and original error. Stale or unmounted requests do not emit |
Slots
| Slot | Scope | Description |
|---|---|---|
| Column prop | { row: TableRowData, column: TableColumnConfig, rowIndex: number } | Custom body cell content |
| header- | { column: TableColumnConfig } | Custom leaf or group header |
filter-<prop> | TableFilterSlotProps | Custom draft panel; value/setValue/confirm/reset/close, bound to the current open session |
| expand | { row: TableRowData, rowIndex: number } | Detail content when expandable is enabled |
| empty | — | Empty content, rendered only when empty and not loading |
| loading | — | Replace the body loading spinner and text; rendered only while loading |
Methods and exposed state
| Name | Signature | Description |
|---|---|---|
| scrollToRow | (key: string | number, options?: TableScrollToRowOptions) => boolean | Navigate to a visible logical row. Defaults to nearest/auto. Returns false for missing or collapsed targets, an unusable viewport, SSR, or an unmounted table. Does not expand ancestors; true means scrolling was requested |
| toggleRowSelection | (row: TableRowData, selected?: boolean) => void | Toggle or set a row's selection |
| toggleAllSelection | () => void | Toggle selection of all available rows, including collapsed tree children |
| clearSelection | () => void | Clear selection |
| setCurrentRow | (row?: TableRowData | null) => void | Set by current data key; unknown rows do nothing, omit or null clears; controlled mode waits for parent |
| clearFilter | (props?: string[]) => void | Clear specified columns or all; follows controlled update/notification rules |
| toggleRowExpansion | (row: TableRowData, expanded?: boolean) => void | Toggle a detail row when expandable, otherwise a tree node |
| expandAll | () => void | Expand available rows; does not fetch lazy children or expand detail rows in accordion mode |
| collapseAll | () => void | Collapse all rows |
| sort | (prop: string, order: TableSortOrder) => void | Update sorting and emit update:sortState, without sort-change; controlled mode requires parent updates |
| clearSort | () => void | Clear sorting and emit update:sortState; query remote data explicitly |
| updateLayout | () => void | Recompute viewport fill height and table layout; safe after unmount |
| selection | Readonly<TableRowData[]> | Frozen shallow array of known selected rows in key order; row object identity is preserved |
| sortState | Readonly<TableSortState> | Deeply read-only current sort state; change it with props or methods |
Types
import type {
TableProps,
TableColumnConfig,
TableRowData,
TableSortState,
TableSortOrder,
TableSize,
TableAlign,
TableLayout,
TableTreeProps,
TableLoadMethod,
TableLoadErrorContext,
TableSummaryMethod,
TableSummaryMethodParams,
TableSpanMethod,
TableSpanMethodParams,
TableExpose,
TableScrollToRowOptions
} from '@nscode/handy-ui'
type TableSize = 'large' | 'default' | 'small'
type TableAlign = 'left' | 'center' | 'right'
type TableLayout = 'fixed' | 'auto'
type TableSortOrder = 'ascending' | 'descending' | null
interface TableSortState {
prop: string
order: TableSortOrder
}
interface TableTreeProps {
children?: string
isLeaf?: string | ((row: TableRowData) => boolean)
}
type TableLoadMethod = (row: TableRowData) => Promise<TableRowData[]>
interface TableLoadErrorContext {
row: TableRowData
key: string | number
error: unknown
}
interface TableScrollToRowOptions {
align?: 'start' | 'center' | 'end' | 'nearest'
behavior?: ScrollBehavior
}
type TableFilterKey = string | number
type TableFilterValue = Record<string, TableFilterKey[]>
interface TableFilterOption {
label: string
value: TableFilterKey
}
interface TableFilterSlotProps {
value: TableFilterKey[]
setValue: (value: TableFilterKey[]) => void
confirm: () => void
reset: () => void
close: () => void
}
interface TableCurrentChangeContext {
row: TableRowData | null
previousKey: string | number | null
previousRow: TableRowData | null
}
interface TableExpose {
updateLayout: () => void
clearFilter: (props?: string[]) => void
scrollToRow: (key: string | number, options?: TableScrollToRowOptions) => boolean
setCurrentRow: (row?: TableRowData | null) => void
toggleRowSelection: (row: TableRowData, selected?: boolean) => void
toggleAllSelection: () => void
clearSelection: () => void
toggleRowExpansion: (row: TableRowData, expanded?: boolean) => void
expandAll: () => void
collapseAll: () => void
sort: (prop: string, order: TableSortOrder) => void
clearSort: () => void
readonly selection: readonly TableRowData[]
readonly sortState: Readonly<TableSortState>
}
Type component refs as TableExpose. Only isLeaf=false marks a lazy row; true or an absent flag with no children is a leaf. Actual non-empty children take precedence over the flag. For a legacy backend field, map isLeaf: (row) => !row.hasChildren.