Table 表格
展示多行结构相同的数据。支持排序、多选、固定表头和固定列、树形数据(可懒加载)、展开行、合计行、合并单元格、多级表头、拖动调整列宽和超长省略,单元格内容可以用格式化函数或插槽自定义。
引入
import { HuiTable } from '@nscode/handy-ui'
基础用法
data 传行数据,columns 传列配置。每一列用 prop 指定取行数据里的哪个字段,label 是表头文字。
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'age', label: '年龄', width: 80 },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, address: '上海市浦东新区' },
{ id: 3, name: '王五', age: 25, address: '广州市天河区' }
]
</script>
<template>
<HuiTable :data="data" :columns="columns" />
</template>
不传 columns 时,按第一行数据的字段名生成列,表头显示字段名。
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, address: '上海市浦东新区' },
{ id: 3, name: '王五', age: 25, address: '广州市天河区' }
]
</script>
<template>
<HuiTable :data="data" />
</template>
嵌套字段与自定义取值
prop 可以写对象或数组路径,例如 product.name、items[0].qty。行上有同名字面量键时优先取该键,即使值是 undefined,也不再回退读取路径。路径中间为空时得到 undefined。
accessor(row) 优先于 prop,用于计算金额等派生值。显示、formatter、默认排序和默认合计共用这个原始结果;formatter 只改变显示文字,自定义 sortMethod、summaryMethod 仍接收原始行数据。取值函数应保持纯函数,不修改行数据。
<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: '笔记本' }, items: [{ qty: 2 }], price: 6 },
{ id: 2, product: { name: '水笔' }, items: [{ qty: 3 }], price: 2 }
])
const columns: TableColumnConfig[] = [
{ prop: 'product.name', label: '商品' },
{ prop: 'items[0].qty', label: '数量', sortable: true },
{
prop: 'amount',
label: '金额',
accessor: (row) => row.items[0].qty * row.price,
formatter: (_row, _column, value) => `${value} 元`,
sortable: true
}
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="data[0].items[0].qty++">增加笔记本数量</HuiButton>
<HuiTable :data="data" :columns="columns" show-summary border />
</HuiSpace>
</template>
prop 仍是排序状态、列宽记录与插槽的标识。带点的单元格插槽写为动态名称 #[`product.name`]="{ row }",表头插槽写为 #[`header-product.name`],不要把点号写成插槽修饰符。
斑马纹和边框
stripe 让偶数行带底色,border 给表格和单元格加边框,两个可以同时用。下面依次是 stripe、border、stripe 加 border:
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'age', label: '年龄', width: 80 },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, address: '上海市浦东新区' },
{ id: 3, name: '王五', age: 25, address: '广州市天河区' },
{ id: 4, name: '赵六', age: 41, address: '深圳市南山区' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p class="demo-label">stripe</p>
<HuiTable :data="data" :columns="columns" stripe />
</div>
<div>
<p class="demo-label">border</p>
<HuiTable :data="data" :columns="columns" border />
</div>
<div>
<p class="demo-label">stripe + border</p>
<HuiTable :data="data" :columns="columns" stripe border />
</div>
</HuiSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
尺寸
size 可选 large、default、small。单元格内边距分别是 16、12、8px,字号是 14、14、12px:表格是成片的数据,large 也用 14px 字,三档主要靠内边距区分。多选列的复选框跟着表格的尺寸(方框 18、16、14px)。不写 size 时跟随 ConfigProvider,都没有时是 default。
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'age', label: '年龄', width: 80 },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, address: '上海市浦东新区' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p class="demo-label">large</p>
<HuiTable :data="data" :columns="columns" size="large" selectable border />
</div>
<div>
<p class="demo-label">default</p>
<HuiTable :data="data" :columns="columns" selectable border />
</div>
<div>
<p class="demo-label">small</p>
<HuiTable :data="data" :columns="columns" size="small" selectable border />
</div>
</HuiSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
列宽和对齐
列的 width 传数字时单位是 px,也可以传带单位的字符串(如 '20%')。默认 tableLayout="fixed",没设宽度的列平分剩下的空间。align 可选 left(默认)、center、right,同时作用于表头和单元格。下面表头里写了每一列用的值:
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID(160px,center)', width: 160, align: 'center' },
{ prop: 'name', label: '姓名(20%,left)', width: '20%' },
{ prop: 'age', label: '年龄(200px,right)', width: 200, align: 'right' },
{ prop: 'address', label: '地址(不设宽度)' }
]
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, address: '上海市浦东新区' }
]
</script>
<template>
<HuiTable :data="data" :columns="columns" border />
</template>
列宽随内容
tableLayout="auto" 按内容分配列宽,单元格不换行;表格比容器宽时横向滚动。下面同一份数据对比 fixed 和 auto:maxWidth 只在 auto 生效,配合 showOverflowTooltip 可以悬停查看被省略的全文。数字宽度单位为 px,字符串可写 rem 等 CSS 长度。
<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: '短名称',
description: '北京市朝阳区望京科技园的一段较长地址,用来观察超出最大宽度后的省略效果',
amount: 12
},
{ id: 2, name: '名称比较长的第二条数据', description: '上海市浦东新区', amount: 25 }
])
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '名称:min 100 / max 160', minWidth: 100, maxWidth: 160, fixed: 'left' },
{ prop: 'description', label: '地址:max 16rem', maxWidth: '16rem', showOverflowTooltip: true },
{ prop: 'amount', label: '数量:width 110', width: 110, align: 'right' }
]
const changeContent = () => {
longer.value = !longer.value
data.value[1].name = longer.value
? '原位更新后名字变得更长,固定列的偏移也会重新测量'
: '短名称'
}
</script>
<template>
<HuiSpace direction="vertical" fill style="max-width: 640px">
<HuiButton @click="changeContent">切换名称长度</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>
明确设置 width 或拖动调宽后,单元格的宽度、最小宽度、最大宽度都采用该值,优先于 minWidth、maxWidth。没有明确宽度时才使用这两个边界。确定长度按包含两侧内边距和列边框的盒子计算;含 % 的宽度只写在单元格上,内容盒采用 max-width:100%,避免再次按百分比缩窄。树缩进、展开箭头与排序图标也计入内容可用空间。分组标题不使用分组列自己的宽度配置,实际宽度由叶子列决定。
原生 auto 布局会在表格撑满容器时分配额外空白,实际 th、td 可能比声明的宽度或 maxWidth 更宽。组件单独约束内部内容盒,保证文字仍按声明上限省略;不要将 maxWidth 当作实际单元格外框的绝对上限。建议用 px、rem 等确定长度;百分比相对于原生表格布局计算,不适合作为严格上限。
下面的百分比只参与原生列宽分配。修改实际展示内容后重新测量固定偏移;未展示的业务字段变化不会遍历整行或触发测量。加载遮罩留给浏览器处理滚轮和触摸,中央自定义按钮仍可使用。
<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: `客户${index + 1}`,
address: '项目地址与说明',
amount: (index + 1) * 10,
revision: 0
}))
)
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '名称20%', width: '20%', fixed: 'left' },
{ prop: 'address', label: '地址60%', width: '60%' },
{ prop: 'amount', label: '金额20%', width: '20%' }
]
const rename = () => {
data[0].name += '(更新)'
}
const updateMetadata = () => {
data[0].revision++
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><span>loading</span><HuiSwitch v-model="loading" /><HuiButton @click="rename"
>更新展示内容</HuiButton
><HuiButton @click="updateMetadata">只改未展示字段</HuiButton
><span>修订 {{ data[0].revision }}</span></HuiSpace
>
<HuiTable
:data="data"
:columns="columns"
table-layout="auto"
:height="240"
:loading="loading"
show-summary
selectable
>
<template #loading
><HuiSpace
><span>加载中,表体可原生滚动</span
><HuiButton size="small" @click="loading = false">结束本次加载</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('拖动表头右边缘,或聚焦把手后按左右方向键')
const columns: TableColumnConfig[] = [
{
prop: 'group',
label: '资料分组',
children: [
{ prop: 'name', label: '树名称', maxWidth: 180, showOverflowTooltip: true, fixed: 'left' },
{ prop: 'amount', label: '数量', width: '7rem', align: 'right' }
]
},
{ prop: 'remark', label: '说明:max 12rem', maxWidth: '12rem', showOverflowTooltip: true }
]
const data = [
{
id: 1,
name: '父节点名称较长,超过上限会显示省略号',
amount: 10,
remark: '双击单元格、排序等已有交互继续有效',
children: [
{
id: 2,
name: '带有一级缩进的子节点名称同样较长',
amount: 5,
remark: '缩进和箭头也在最大宽度以内'
}
]
}
]
const onResize = (column: TableColumnConfig, width: number) => {
resized.value = `${column.label}:${width}px,之后按此宽度显示内容`
}
</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 }">当前记录:{{ row.name }}</template>
</HuiTable>
<span>{{ resized }}</span>
</HuiSpace>
</template>
排序
列上设 sortable: true 后可以点表头排序,顺序是升序、降序、取消排序,每次变化触发 sort-change。数字按大小比较,其他值转成字符串比较,空值(null、undefined)升序时排在最后(下面“入职日期”列赵六的那一行)。
default-sort 指定一开始的排序,order 可选 ascending(升序)、descending(降序)。下面第一个表格一开始按年龄降序,第二个按入职日期升序:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSortState } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80, sortable: true },
{ prop: 'name', label: '姓名', width: 100 },
{ prop: 'age', label: '年龄', width: 100, sortable: true },
{
prop: 'joinDate',
label: '入职日期',
width: 140,
sortable: true,
formatter: (row, column, value) => (value ? String(value) : '—')
},
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', age: 28, joinDate: '2021-03-15', address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, joinDate: '2018-07-01', address: '上海市浦东新区' },
{ id: 3, name: '王五', age: 25, joinDate: '2023-11-20', address: '广州市天河区' },
{ id: 4, name: '赵六', age: 41, joinDate: null, address: '深圳市南山区' }
]
const sortText = ref('点表头排序试试')
const handleSortChange = (sortState: TableSortState) => {
sortText.value = `sort-change:prop = ${sortState.prop},order = ${sortState.order}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable
:data="data"
:columns="columns"
:default-sort="{ prop: 'age', order: 'descending' }"
@sort-change="handleSortChange"
/>
<p>{{ sortText }}</p>
<HuiTable
:data="data"
:columns="columns"
:default-sort="{ prop: 'joinDate', order: 'ascending' }"
/>
</HuiSpace>
</template>
自己处理排序
sortable: 'custom' 时表格只切换表头的排序状态并触发 sort-change,不改变行的顺序。适合由后端排序:在事件里重新请求数据。下面用定时器模拟请求:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSortState } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 140 },
{ prop: 'age', label: '年龄', sortable: 'custom' }
]
const source = [
{ id: 1, name: '张三', age: 28 },
{ id: 2, name: '李四', age: 32 },
{ id: 3, name: '王五', age: 25 }
]
const data = ref(source.slice())
const status = ref('')
// 模拟后端排序:0.5 秒后返回排好的数据
const handleSortChange = ({ prop, order }: TableSortState) => {
status.value = `正在请求:sort=${prop},order=${order ?? '不排序'}……`
window.setTimeout(() => {
if (prop !== 'age' || !order) {
data.value = source.slice()
} else {
const direction = order === 'ascending' ? 1 : -1
data.value = source.slice().sort((a, b) => (a.age - b.age) * direction)
}
status.value = '已按返回的顺序显示'
}, 500)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="data" :columns="columns" @sort-change="handleSortChange" />
<p>{{ status || '点“年龄”表头试试' }}</p>
</HuiSpace>
</template>
受控排序和外部回填
v-model:sort-state 同步 { prop, order },order 使用 ascending、descending、null。传了 sort-state 后优先于 default-sort,表头和本地排序都以传入值为准。点击先发 update:sortState 请求,再发 sort-change;父组件不回填时,箭头和行顺序保持不变。外部直接赋值不发这两个事件。
sortState 属性存在且值为 undefined 时仍受控,按无排序显示,不采用 defaultSort;移除属性后才恢复此前的内部自持值。只有 sortable: true 的列参与本地排序;未开启排序的列即使被 sort()、defaultSort 或受控值指定,也不会重排行数据。
<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: '甲', age: 30 },
{ id: 2, name: '乙', age: 20 },
{ id: 3, name: '丙', age: 25 }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄', sortable: true }
]
const sort = ref<TableSortState | undefined>({ prop: 'age', order: 'ascending' })
const frozen: TableSortState = { prop: 'age', order: 'ascending' }
const requested = ref('尚未请求更新')
const record = (value: TableSortState) => {
requested.value = `${value.prop} / ${value.order ?? '不排序'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>v-model:sort-state 自动回填</p>
<HuiTable v-model:sort-state="sort" :data="data" :columns="columns" />
<HuiSpace
><HuiButton @click="sort = { prop: 'age', order: 'descending' }">外部设为降序</HuiButton
><HuiButton @click="sort = undefined">置回 undefined 清排序</HuiButton
><span>{{ sort?.prop || '无' }} / {{ sort?.order ?? '不排序' }}</span></HuiSpace
>
</div>
<div>
<p>只监听请求,不回填:点击后保持升序;default-sort 不覆盖受控值</p>
<HuiTable
:sort-state="frozen"
:default-sort="{ prop: 'age', order: 'descending' }"
:data="data"
:columns="columns"
@update:sort-state="record"
/>
<p>最近请求:{{ requested }}</p>
</div>
</HuiSpace>
</template>
排序循环和本地比较函数
列配置的 sortOrders 不含 null 就不能通过表头取消,单个值时每次都使用这个值,空数组回到默认三态。切换到另一列或当前顺序不在数组里时,从首项开始。
sortMethod(a, b, order) 只用于 sortable: true 的本地排序。按升序返回比较结果,表格在降序时统一取反;order 便于特殊处理空值。下面“金额”的空值在两种顺序下都排最后,“年龄”只在升降序间切换,“评分”只能降序。
<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: '甲', age: 30, score: 90, amount: null },
{ id: 2, name: '乙', age: 20, score: 70, amount: 80 },
{ id: 3, name: '丙', 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: '姓名' },
{ prop: 'age', label: '年龄:升降序', sortable: true, sortOrders: ['ascending', 'descending'] },
{ prop: 'score', label: '评分:仅降序', sortable: true, sortOrders: ['descending'] },
{
prop: 'amount',
label: '金额:空值末尾',
sortable: true,
sortMethod: compareAmount,
formatter: (row) => (row.amount == null ? '未填写' : 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>当前排序:{{ sort.prop || '无' }} / {{ sort.order ?? '不排序' }}</span>
</HuiSpace>
</template>
排序和清除方法
sort(prop, order)、clearSort() 会发 update:sortState,不发 sort-change。远程排序的重置按钮里,清排序后自行查询一次。下面的查询次数可以核对:点表头、调用方法或重置,各只查询一次。sortState 在组件 ref 上深只读,用方法或受控属性修改。
<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: '甲', age: 30 },
{ id: 2, name: '乙', age: 20 },
{ id: 3, name: '丙', age: 25 }
]
const data = ref(source.slice())
const sort = ref<TableSortState>({ prop: '', order: null })
const requests = ref(0)
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄', 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() 并查询</HuiButton
><span>查询 {{ requests }} 次</span></HuiSpace
>
<HuiTable
ref="tableRef"
v-model:sort-state="sort"
:data="data"
:columns="columns"
@sort-change="query"
/>
</HuiSpace>
</template>
多选
selectable 在最左边加一列复选框。表头的复选框用来全选,只选了一部分时显示成半选,选中的行带浅色底。选中的行通过 selection-change 拿到,也可以通过 ref 调用方法来改:
toggleRowSelection(row, selected?):切换一行,传了selected时直接设成选中或不选中。toggleAllSelection():已经全选时取消全选,否则全选。clearSelection():清空。
点复选框时还会触发 select(某一行变化)或 select-all(点表头的全选框)。点行默认不勾选,下面在 row-click 里调用了 toggleRowSelection,点行也能勾选。
<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 } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', address: '北京市朝阳区' },
{ id: 2, name: '李四', address: '上海市浦东新区' },
{ id: 3, name: '王五', address: '广州市天河区' }
]
const tableRef = ref<TableExpose>()
const selectedNames = ref<string[]>([])
const lastEvent = ref('')
const handleSelectionChange = (selection: TableRowData[]) => {
selectedNames.value = selection.map((row) => String(row.name))
}
const handleSelect = (selection: TableRowData[], row: TableRowData) => {
lastEvent.value = `select:${row.name},现在选了 ${selection.length} 行`
}
const handleSelectAll = (selection: TableRowData[]) => {
lastEvent.value = `select-all:现在选了 ${selection.length} 行`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton size="small" @click="tableRef?.toggleRowSelection(data[0], true)">
选中第一行
</HuiButton>
<HuiButton size="small" @click="tableRef?.toggleRowSelection(data[1])">切换第二行</HuiButton>
<HuiButton size="small" @click="tableRef?.toggleAllSelection()">全选 / 取消全选</HuiButton>
<HuiButton size="small" @click="tableRef?.clearSelection()">清空</HuiButton>
</HuiSpace>
<HuiTable
ref="tableRef"
:data="data"
:columns="columns"
selectable
@selection-change="handleSelectionChange"
@select="handleSelect"
@select-all="handleSelectAll"
@row-click="(row) => tableRef?.toggleRowSelection(row)"
/>
<p>已选:{{ selectedNames.join('、') || '无' }}</p>
<p v-if="lastEvent">{{ lastEvent }}</p>
</HuiSpace>
</template>
受控勾选
v-model:selected-keys 接收原始主键数组,数字主键保持数字。传了 selected-keys 后,复选框和 selection 都以外部值为准;不回填时 UI 不变。update:selectedKeys 请求新 key,select、select-all 和 selection-change 使用这次操作提议的新行数组,即使父组件拒绝回填也一样。
同一 tick 连续调用单行切换、全选和清空方法,会按本批最新提议合并;父级回填后以回填值为准,不回填时下一批重新使用父值。显式 selectedKeys=undefined 仍为受控空勾选;移除属性才恢复此前内部值,被拒绝的提议不写入内部值。
<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: '甲' },
{ id: 2, name: '乙' },
{ id: 3, name: '丙' }
]
const columns = [{ prop: 'name', label: '姓名' }]
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('尚未请求更新')
const event = ref('尚未操作')
const recordKeys = (value: (string | number)[]) => {
request.value = JSON.stringify(value)
}
const recordRows = (value: TableRowData[]) => {
event.value = value.map((row) => row.name).join('、') || '无'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>自动接受回填</p>
<HuiTable
ref="tableRef"
v-model:selected-keys="keys"
:data="rows"
:columns="columns"
selectable
/>
<HuiSpace
><HuiButton @click="keys = [1, 3]">外部选中 1、3</HuiButton
><HuiButton @click="selectEach">同 tick 逐行勾选</HuiButton
><span>keys:{{ keys }}</span></HuiSpace
>
</div>
<div>
<p>只监听,不回填,界面保持选中乙</p>
<HuiTable
:selected-keys="frozen"
:data="rows"
:columns="columns"
selectable
@update:selected-keys="recordKeys"
@selection-change="recordRows"
/>
<p>请求 keys:{{ request }};事件新行:{{ event }}</p>
</div>
</HuiSpace>
</template>
跨页保留勾选
reserve-selection 保留不在当前数据中的选中 key 和已经见过的行对象。全选、取消全选只影响当前页,表头全选和半选也只按当前页判断;树形数据还包括当前数据里收起的子行。clearSelection() 清掉所有页。
<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: '甲' },
{ id: 2, name: '乙' }
],
[
{ id: 3, name: '丙' },
{ id: 4, name: '丁' }
]
]
const rows = computed(() => pages[page.value])
const keys = ref<(string | number)[]>([])
const columns = [
{ prop: 'id', label: 'ID' },
{ prop: 'name', label: '姓名' }
]
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">第 1 页</HuiButton>
<HuiButton :disabled="page === 1" @click="page = 1">第 2 页</HuiButton>
<HuiButton @click="tableRef?.toggleAllSelection()">切换当前页全选</HuiButton>
<HuiButton @click="tableRef?.clearSelection()">清除所有页勾选</HuiButton>
</HuiSpace>
<HuiTable
ref="tableRef"
v-model:selected-keys="keys"
:data="rows"
:columns="columns"
row-key="id"
reserve-selection
selectable
/>
<span>当前第 {{ page + 1 }} 页;keys:{{ keys }};选中:{{ names || '无' }}</span>
</HuiSpace>
</template>
当前页同 key 换了新对象时,缓存使用新对象;取消勾选的其他页行不再保留。selection 按所选 key 的顺序返回已经找到的行,尚未取过数据的 key 不会虚构行对象。组件 ref 和内部 context 上的 selection 为冻结的浅拷贝数组,不能增删选中项;行对象保持传入身份和原有可编辑性。修改勾选请走 key 属性或方法。
路由回填和异步取数
从路由回填 key 时建议开启 reserve-selection。key 可以先到、行数据后到:数据取到后复选框及 selection 会自动对应。不开跨页保留时,只在数据变化时请求移除当前数据中不存在的 key;单独给 selected-keys 赋值不会立即清除它们。
<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('路由先回填 key=3,行数据尚未取到')
const columns = [
{ prop: 'id', label: 'ID' },
{ prop: 'name', label: '姓名' }
]
const load = async () => {
loading.value = true
try {
await new Promise((resolve) => setTimeout(resolve, 400))
rows.value = [
{ id: 3, name: '路由选中的记录' },
{ id: 4, name: '另一条记录' }
]
status.value = '数据已到,key=3 自动勾选'
} finally {
loading.value = false
}
}
const read = () => {
status.value = `selection:${tableRef.value!.selection.map((row) => row.name).join('、') || '没有已取到的行'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton :loading="loading" @click="load">异步取数据</HuiButton
><HuiButton @click="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>
行的唯一标识
表格用 row-key 区分每一行,默认取行数据的 id 字段。唯一字段不叫 id 时传字段名(上面的表格),或者传一个返回字符串或数字的函数(下面的表格)。跨页保留时每一行都必须有稳定且唯一的 key;缺失或当前数据里重复时,开发环境会警告。
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
const data = [
{ code: 'A001', name: '螺丝', stock: 1200 },
{ code: 'A002', name: '螺母', stock: 860 },
{ code: 'A003', name: '垫片', stock: 430 }
]
const getRowKey = (row: TableRowData) => `row-${row.code}`
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="data" row-key="code" selectable />
<HuiTable :data="data" :row-key="getRowKey" selectable />
</HuiSpace>
</template>
固定表头
设了 height 或 max-height 后,内容超出时表体滚动,表头一直停在上面。height 是固定高度;max-height 在行数少时按内容高度显示。数字的单位是 px,也可以传 '50vh' 这样的字符串。
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'address', label: '地址' }
]
const surnames = ['张', '王', '李', '赵', '刘']
const givenNames = ['伟', '芳', '娜', '敏']
const districts = ['朝阳区', '海淀区', '东城区', '西城区', '丰台区']
const data = Array.from({ length: 20 }, (_, index) => ({
id: index + 1,
name: `${surnames[index % 5]}${givenNames[index % 4]}`,
address: `北京市${districts[index % 5]}`
}))
const fewRows = data.slice(0, 3)
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p class="demo-label">:height="300"(20 行)</p>
<HuiTable :data="data" :columns="columns" :height="300" border />
</div>
<div>
<p class="demo-label">:max-height="260"(20 行,超出后滚动)</p>
<HuiTable :data="data" :columns="columns" :max-height="260" border />
</div>
<div>
<p class="demo-label">:max-height="260"(3 行,按内容高度)</p>
<HuiTable :data="fewRows" :columns="columns" :max-height="260" border />
</div>
</HuiSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
固定列
列上设 fixed: 'left' 或 fixed: 'right',横向滚动时这一列停在左边或右边。要让表格出现横向滚动,每一列都要设 width,并且宽度加起来超过表格的宽度。有左固定列并且开了 selectable 时,复选框列也跟着固定。有内容滚到固定列下面时,固定列靠里的一侧会显示一道阴影。
<script setup lang="ts">
import { HuiButton, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 120, fixed: 'left' },
{ prop: 'age', label: '年龄', width: 200 },
{ prop: 'phone', label: '电话', width: 300 },
{ prop: 'email', label: '邮箱', width: 300 },
{ prop: 'address', label: '地址', width: 400 },
{ prop: 'action', label: '操作', width: 120, fixed: 'right' }
]
const data = [
{
id: 1,
name: '张三',
age: 28,
phone: '13800000001',
email: 'zhangsan@example.com',
address: '北京市朝阳区'
},
{
id: 2,
name: '李四',
age: 32,
phone: '13800000002',
email: 'lisi@example.com',
address: '上海市浦东新区'
},
{
id: 3,
name: '王五',
age: 25,
phone: '13800000003',
email: 'wangwu@example.com',
address: '广州市天河区'
}
]
</script>
<template>
<div style="max-width: 800px">
<HuiTable :data="data" :columns="columns" selectable border>
<template #action>
<HuiButton size="small" type="primary" variant="link">编辑</HuiButton>
</template>
</HuiTable>
</div>
</template>
格式化单元格
列的 formatter 接收行数据、列配置和单元格的值,返回要显示的字符串。
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const statusText: Record<string, string> = { active: '在职', leave: '休假', quit: '离职' }
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'age', label: '年龄', width: 100, formatter: (row, column, value) => `${value} 岁` },
{
prop: 'status',
label: '状态',
width: 100,
formatter: (row, column, value) => statusText[String(value)] ?? '未知'
},
{
prop: 'salary',
label: '月薪',
align: 'right',
formatter: (row) => `¥ ${Number(row.salary).toLocaleString()}`
}
]
const data = [
{ id: 1, name: '张三', age: 28, status: 'active', salary: 12000 },
{ id: 2, name: '李四', age: 32, status: 'leave', salary: 18500 },
{ id: 3, name: '王五', age: 25, status: 'quit', salary: 9800 }
]
</script>
<template>
<HuiTable :data="data" :columns="columns" />
</template>
自定义单元格
要在单元格里放标签、按钮等内容时,用和列的 prop 同名的插槽,参数是 row、column、rowIndex。写了插槽的列不再用 formatter。操作列这类不对应字段的列,prop 随便起一个不重复的名字即可。单元格里的按钮不想触发 row-click 时,点击事件加 .stop。
<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: '姓名', width: 140 },
{ prop: 'status', label: '状态', width: 120 },
{ prop: 'address', label: '地址' },
{ prop: 'action', label: '操作', 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(
'删除“' + target.name + '”这一行及其当前内容?其他行保留。',
'删除行',
{ confirmButtonText: '删除', confirmButtonType: 'danger' }
)
if (!alive) return
if (version !== revision || data.value !== collection || !collection.includes(target)) {
HuiMessage.info('行数据已变化,本次删除已取消,请重新操作')
return
}
data.value = collection.filter((item) => item !== target)
} catch {
// 取消或关闭确认框时保留全部行。
} 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' ? '启用' : '停用' }}
</HuiTag>
</template>
<template #action="{ row }">
<HuiSpace :size="4">
<HuiButton
size="small"
type="primary"
variant="link"
@click.stop="HuiMessage.info(`查看${row.name}`)"
>
查看
</HuiButton>
<HuiButton
size="small"
type="danger"
variant="link"
:disabled="removing"
@click.stop="remove(row)"
>
删除
</HuiButton>
</HuiSpace>
</template>
</HuiTable>
<HuiSpace wrap>
<HuiButton
size="small"
:disabled="data.length === source.length"
@click="data = source.slice()"
>
恢复删除的行
</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
空数据
data 是空数组时显示 empty-text,默认随语言,中文是“暂无数据”。要放图片或按钮时用 empty 插槽,例如放一个 HuiEmpty。
<script setup lang="ts">
import { HuiButton, HuiEmpty, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'age', label: '年龄', width: 80 },
{ prop: 'address', label: '地址' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="[]" :columns="columns" />
<HuiTable :data="[]" :columns="columns" empty-text="没有符合条件的记录" />
<HuiTable :data="[]" :columns="columns">
<template #empty>
<HuiEmpty description="还没有员工,先去新建一个">
<HuiButton type="primary" icon="plus">新建员工</HuiButton>
</HuiEmpty>
</template>
</HuiTable>
</HuiSpace>
</template>
隐藏表头
show-header 设为 false 后不渲染表头。
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'age', label: '年龄', width: 80 },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 32, address: '上海市浦东新区' },
{ id: 3, name: '王五', age: 25, address: '广州市天河区' }
]
</script>
<template>
<HuiTable :data="data" :columns="columns" :show-header="false" border />
</template>
自定义类名
row-class-name、cell-class-name、header-cell-class-name 可以传字符串,也可以传函数按行、按列返回类名。列配置里的 className 会同时加到这一列的表头和单元格上。组件的样式带 scoped,自己的类要写在全局样式里,或者在 scoped 样式里用 :deep()。
下面 60 岁及以上的行标红(row-class-name),年龄不到 30 的单元格标绿(cell-class-name),可排序列的表头用主色(header-cell-class-name),“年龄”列整列加粗(className):
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 140 },
{ prop: 'age', label: '年龄', width: 120, sortable: true, className: 'col-age' },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', age: 28, address: '北京市朝阳区' },
{ id: 2, name: '李四', age: 62, address: '上海市浦东新区' },
{ id: 3, name: '王五', age: 45, address: '广州市天河区' }
]
const rowClassName = (row: TableRowData) => (Number(row.age) >= 60 ? 'row-warning' : '')
const cellClassName = (row: TableRowData, column: TableColumnConfig) =>
column.prop === 'age' && Number(row.age) < 30 ? 'cell-young' : ''
const headerCellClassName = (column: TableColumnConfig) =>
column.sortable ? 'header-sortable' : ''
</script>
<template>
<HuiTable
:data="data"
:columns="columns"
:row-class-name="rowClassName"
:cell-class-name="cellClassName"
:header-cell-class-name="headerCellClassName"
/>
</template>
<style scoped>
:deep(.row-warning) {
color: var(--hui-color-danger);
}
:deep(.cell-young) {
color: var(--hui-color-success);
}
:deep(th.header-sortable) {
color: var(--hui-color-primary);
}
:deep(.col-age) {
font-weight: 600;
}
</style>
点击事件
点单元格时先触发 cell-click,再触发 row-click。点复选框那一列不触发这两个事件。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 140 },
{ prop: 'address', label: '地址' }
]
const data = [
{ id: 1, name: '张三', address: '北京市朝阳区' },
{ id: 2, name: '李四', address: '上海市浦东新区' }
]
const cellText = ref('')
const rowText = ref('')
const handleCellClick = (
row: TableRowData,
column: TableColumnConfig,
cell: HTMLTableCellElement
) => {
cellText.value = `cell-click:${column.label}列,单元格内容“${cell.textContent?.trim()}”`
}
const handleRowClick = (row: TableRowData, column: TableColumnConfig) => {
rowText.value = `row-click:${row.name}这一行,点在“${column.label}”列`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable
:data="data"
:columns="columns"
selectable
@row-click="handleRowClick"
@cell-click="handleCellClick"
/>
<p>{{ cellText || '点单元格试试(点复选框不触发)' }}</p>
<p v-if="rowText">{{ rowText }}</p>
</HuiSpace>
</template>
双击与右键菜单
数据单元格触发 row-dblclick、row-contextmenu,参数均为行、列、原始事件;选择列、展开列和表头不触发。组件不阻止默认行为或冒泡,调用菜单的 open 后才接管原生菜单。编辑、删除的完整示例见 ContextMenu。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTable, HuiContextMenu, HuiDropdownItem, HuiMessage, HuiSpace } from '@nscode/handy-ui'
import type { ContextMenuExpose, TableColumnConfig, TableRowData } from '@nscode/handy-ui'
interface CellTarget {
row: TableRowData
column: TableColumnConfig
}
const menu = ref<ContextMenuExpose>()
const latest = ref('')
const data = [
{ id: 1, name: '设计稿' },
{ id: 2, name: '归档资料' }
]
const columns: TableColumnConfig[] = [{ prop: 'name', label: '文件名' }]
const target = (data: unknown) => data as CellTarget | undefined
const show = (_command: unknown, data: unknown) => {
const selected = target(data)
if (selected) HuiMessage.info(`${selected.row.name} / ${selected.column.label}`)
}
const onDoubleClick = (row: TableRowData, column: TableColumnConfig) => {
latest.value = `双击:${row.name} / ${column.label}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable
:data="data"
:columns="columns"
row-key="id"
selectable
@row-dblclick="onDoubleClick"
@row-contextmenu="(row, column, event) => menu?.open(event, { row, column })"
>
<template #name="{ row }"
><span tabindex="0">{{ row.name }}</span></template
>
</HuiTable>
<span>{{ latest || '尚无双击记录' }}</span>
</HuiSpace>
<HuiContextMenu ref="menu" @command="show">
<template #default="{ data }">
<HuiDropdownItem command="view" icon="eye">查看 {{ target(data)?.row.name }}</HuiDropdownItem>
</template>
</HuiContextMenu>
</template>
树形数据
行数据里有 children 数组时按树形显示:第一列带缩进和展开按钮,点按钮展开或收起子行,每次变化触发 expand-change。树形数据要求每一行(包括子行)都有唯一的 row-key。
default-expand-all 一开始展开所有层级。也可以通过 ref 调用 expandAll()、collapseAll() 一次展开或收起全部,toggleRowExpansion(row, expanded?) 切换某一行。
<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 } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '部门', width: 220 },
{ prop: 'leader', label: '负责人', width: 120 },
{ prop: 'count', label: '人数', width: 100, align: 'right', sortable: true },
{ prop: 'phone', label: '电话' }
]
const data = [
{
id: 1,
name: '总经办',
leader: '张伟',
count: 6,
phone: '010-80001000',
children: [
{
id: 11,
name: '行政部',
leader: '王芳',
count: 12,
phone: '010-80001100',
children: [
{ id: 111, name: '前台', leader: '李娜', count: 3, phone: '010-80001101' },
{ id: 112, name: '后勤组', leader: '赵敏', count: 5, phone: '010-80001102' }
]
},
{ id: 12, name: '财务部', leader: '刘静', count: 8, phone: '010-80001200' }
]
},
{
id: 2,
name: '研发中心',
leader: '陈强',
count: 46,
phone: '010-80002000',
children: [
{ id: 21, name: '前端组', leader: '杨洋', count: 15, phone: '010-80002100' },
{ id: 22, name: '后端组', leader: '黄磊', count: 21, phone: '010-80002200' }
]
},
{ id: 3, name: '市场部', leader: '周杰', count: 18, phone: '010-80003000' }
]
const tableRef = ref<TableExpose>()
const lastEvent = ref('')
const handleExpandChange = (
row: TableRowData,
expanded: boolean,
expandedRows: TableRowData[]
) => {
lastEvent.value = `expand-change:${expanded ? '展开' : '收起'}了“${row.name}”,现在展开着 ${expandedRows.length} 行`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton size="small" @click="tableRef?.expandAll()">展开全部</HuiButton>
<HuiButton size="small" @click="tableRef?.collapseAll()">收起全部</HuiButton>
<HuiButton size="small" @click="tableRef?.toggleRowExpansion(data[1])"
>切换“研发中心”</HuiButton
>
</HuiSpace>
<HuiTable
ref="tableRef"
:data="data"
:columns="columns"
default-expand-all
border
@expand-change="handleExpandChange"
/>
<p>{{ lastEvent || '点部门名称前面的箭头试试' }}</p>
</HuiSpace>
</template>
子行数组的字段不叫 children 时,用 tree-props 指定字段名。default-expanded-keys 传一组 row-key,一开始只展开这些行;indent 是每一级缩进的宽度,默认 16px。下面子行放在 cities 字段里,一开始只展开“华东区”,每级缩进 32px:
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '地区', width: 220 },
{ prop: 'stores', label: '门店数', width: 100, align: 'right' },
{ prop: 'manager', label: '区域经理' }
]
const data = [
{
code: 'EC',
name: '华东区',
stores: 128,
manager: '王芳',
cities: [
{ code: 'SH', name: '上海', stores: 56, manager: '李娜' },
{ code: 'HZ', name: '杭州', stores: 41, manager: '赵敏' },
{ code: 'NJ', name: '南京', stores: 31, manager: '孙磊' }
]
},
{
code: 'SC',
name: '华南区',
stores: 97,
manager: '陈强',
cities: [
{ code: 'GZ', name: '广州', stores: 52, manager: '杨洋' },
{ code: 'SZ', name: '深圳', stores: 45, manager: '黄磊' }
]
}
]
</script>
<template>
<HuiTable
:data="data"
:columns="columns"
row-key="code"
:tree-props="{ children: 'cities' }"
:default-expanded-keys="['EC']"
:indent="32"
/>
</template>
懒加载子行
子行要展开时才去请求的,在行上标记 isLeaf: false(字段名可以用 tree-props 改),再传 load 函数。第一次展开时表格调用 load(row),加载期间箭头换成加载图标;通过返回的 Promise 提供子行数组。加载过的行再收起、展开不会重新请求;返回空数组时这一行不再显示箭头;Promise 被拒绝时结束加载、保持收起,再点一次会重新请求。
下面用定时器模拟请求,“西北区”没有下级城市:
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '地区', width: 220 },
{ prop: 'code', label: '编码', width: 120 },
{ prop: 'manager', label: '负责人' }
]
const data = [
{ code: 'EC', name: '华东区', manager: '王芳', isLeaf: false },
{ code: 'SC', name: '华南区', manager: '陈强', isLeaf: false },
{ code: 'NW', name: '西北区', manager: '周杰', isLeaf: false }
]
const cities: Record<string, TableRowData[]> = {
EC: [
{ code: 'SH', name: '上海', manager: '李娜', isLeaf: false },
{ code: 'HZ', name: '杭州', manager: '赵敏' }
],
SH: [
{ code: 'SH-PD', name: '浦东新区', manager: '孙磊' },
{ code: 'SH-XH', name: '徐汇区', manager: '刘静' }
],
SC: [
{ code: 'GZ', name: '广州', manager: '杨洋' },
{ code: 'SZ', name: '深圳', manager: '黄磊' }
]
}
// 模拟接口:0.8 秒后返回下级地区
const load = (row: TableRowData) =>
new Promise<TableRowData[]>((resolve) => {
window.setTimeout(() => resolve(cities[String(row.code)] ?? []), 800)
})
</script>
<template>
<HuiTable :data="data" :columns="columns" row-key="code" :load="load" />
</template>
展开行
expandable 在左边加一列展开按钮,点开后在这一行下面显示 expand 插槽的内容,插槽参数是 row 和 rowIndex。展开、收起时触发 expand-change,参数是这一行、是否展开和展开着的全部行。通过 ref 调用 toggleRowExpansion(row, expanded?) 切换某一行,expandAll()、collapseAll() 展开或收起全部。点展开列不触发 row-click。
<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 } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'orderNo', label: '订单号', width: 180 },
{ prop: 'customer', label: '客户', width: 120 },
{ prop: 'amount', label: '金额(元)', width: 120, align: 'right' },
{ prop: 'createdAt', label: '下单时间' }
]
const data = [
{
id: 1,
orderNo: 'DD202611150001',
customer: '张伟',
amount: 2580,
createdAt: '2026-11-15 09:12',
receiver: '张伟',
phone: '13800001111',
address: '北京市朝阳区建国路 88 号',
goods: '办公椅 × 2、升降桌 × 1'
},
{
id: 2,
orderNo: 'DD202611150002',
customer: '王芳',
amount: 399,
createdAt: '2026-11-15 10:40',
receiver: '王芳',
phone: '13900002222',
address: '上海市浦东新区世纪大道 100 号',
goods: '台灯 × 1'
},
{
id: 3,
orderNo: 'DD202611160003',
customer: '李娜',
amount: 1260,
createdAt: '2026-11-16 14:05',
receiver: '刘静',
phone: '13700003333',
address: '广州市天河区天河路 385 号',
goods: '文件柜 × 3'
}
]
const tableRef = ref<TableExpose>()
const lastEvent = ref('')
const handleExpandChange = (
row: TableRowData,
expanded: boolean,
expandedRows: TableRowData[]
) => {
lastEvent.value = `expand-change:${expanded ? '展开' : '收起'}了 ${row.orderNo},现在展开着 ${expandedRows.length} 行`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton size="small" @click="tableRef?.toggleRowExpansion(data[0])">切换第一行</HuiButton>
<HuiButton size="small" @click="tableRef?.expandAll()">展开全部</HuiButton>
<HuiButton size="small" @click="tableRef?.collapseAll()">收起全部</HuiButton>
</HuiSpace>
<HuiTable
ref="tableRef"
:data="data"
:columns="columns"
expandable
@expand-change="handleExpandChange"
>
<template #expand="{ row }">
<dl class="order-detail">
<dt>收货人</dt>
<dd>{{ row.receiver }}({{ row.phone }})</dd>
<dt>收货地址</dt>
<dd>{{ row.address }}</dd>
<dt>商品</dt>
<dd>{{ row.goods }}</dd>
</dl>
</template>
</HuiTable>
<p>{{ lastEvent || '点左边的箭头展开订单详情' }}</p>
</HuiSpace>
</template>
<style scoped>
.order-detail {
display: grid;
grid-template-columns: 80px 1fr;
gap: 8px;
margin: 0;
}
.order-detail dt {
color: var(--hui-text-color-secondary);
}
.order-detail dd {
margin: 0;
}
</style>
手风琴和默认展开
accordion 让展开行同时只展开一行,展开另一行时前一行自动收起。default-expanded-keys 传一组 row-key,一开始展开这些行;default-expand-all 一开始展开全部。下面一开始展开第二行:
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'dept', label: '部门', width: 140 },
{ prop: 'position', label: '职位' }
]
const data = [
{
id: 1,
name: '张伟',
dept: '研发中心',
position: '前端工程师',
intro: '负责管理后台的页面开发。'
},
{ id: 2, name: '王芳', dept: '财务部', position: '会计', intro: '负责应收应付和月度结账。' },
{
id: 3,
name: '李娜',
dept: '市场部',
position: '市场专员',
intro: '负责线上活动的策划和执行。'
}
]
</script>
<template>
<HuiTable :data="data" :columns="columns" expandable accordion :default-expanded-keys="[2]">
<template #expand="{ row }">
<p class="intro">{{ row.name }}:{{ row.intro }}</p>
</template>
</HuiTable>
</template>
<style scoped>
.intro {
margin: 0;
color: var(--hui-text-color-secondary);
}
</style>
合计行
show-summary 在表尾加一行合计:第一列显示 summary-text(默认随语言,中文是“合计”),其余列把数字类型的值加起来,没有数字的列留空。只合计第一层的行,树形数据的子行不算在里面。设了 height 或 max-height 时合计行和表头一样固定在可视区域里。
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'store', label: '门店', width: 140 },
{ prop: 'city', label: '城市', width: 100 },
{ prop: 'orders', label: '订单数', align: 'right' },
{ prop: 'amount', label: '销售额(元)', align: 'right' }
]
const data = [
{ id: 1, store: '朝阳大悦城店', city: '北京', orders: 1286, amount: 358620.5 },
{ id: 2, store: '陆家嘴店', city: '上海', orders: 1032, amount: 296410.25 },
{ id: 3, store: '天河城店', city: '广州', orders: 874, amount: 213980 },
{ id: 4, store: '万象天地店', city: '深圳', orders: 951, amount: 247300.75 }
]
</script>
<template>
<HuiTable :data="data" :columns="columns" show-summary border />
</template>
summary-method 自定义每一列的内容:参数是 { columns, data }(数据列和第一层的行数据),返回和 columns 一一对应的数组,null、undefined 显示成空。下面合计行的文字改成“本月合计”,销售额加上千分位,城市列显示门店数:
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSummaryMethodParams } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'store', label: '门店', width: 140 },
{ prop: 'city', label: '城市', width: 120 },
{ prop: 'orders', label: '订单数', align: 'right' },
{
prop: 'amount',
label: '销售额(元)',
align: 'right',
formatter: (row, column, value) => Number(value).toLocaleString()
}
]
const data = [
{ id: 1, store: '朝阳大悦城店', city: '北京', orders: 1286, amount: 358620.5 },
{ id: 2, store: '陆家嘴店', city: '上海', orders: 1032, amount: 296410.25 },
{ id: 3, store: '天河城店', city: '广州', orders: 874, amount: 213980 }
]
const summaryMethod = ({ columns, data }: TableSummaryMethodParams) =>
columns.map((column, index) => {
if (index === 0) return '本月合计'
if (column.prop === 'city') return `${data.length} 家门店`
const total = data.reduce((sum, row) => sum + Number(row[column.prop]), 0)
return column.prop === 'amount' ? `¥ ${total.toLocaleString()}` : total
})
</script>
<template>
<HuiTable :data="data" :columns="columns" show-summary :summary-method="summaryMethod" />
</template>
合并单元格
span-method 按行、列决定每个单元格占几行几列。参数是 { row, column, rowIndex, columnIndex }:rowIndex 是排序、展开后看得见的行里的序号,columnIndex 是数据列的序号(不算复选框列、展开列),都从 0 开始。返回 [rowspan, colspan] 或 { rowspan, colspan },不返回时是 1 行 1 列;被合并掉的单元格要返回 [0, 0],这样的单元格不渲染。
下面把同一天的“日期”合并成一格(按数据算出每一天从哪一行开始、有几行);11 月 20 日休息,这一行从“班次”到“联系电话”合并成一格:
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig, TableSpanMethodParams } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'date', label: '日期', width: 140, align: 'center' },
{ prop: 'shift', label: '班次', width: 120 },
{ prop: 'staff', label: '值班人', width: 120 },
{ prop: 'phone', label: '联系电话' }
]
const data = [
{ id: 1, date: '11 月 18 日', shift: '早班', staff: '张伟', phone: '13800001111' },
{ id: 2, date: '11 月 18 日', shift: '中班', staff: '王芳', phone: '13900002222' },
{ id: 3, date: '11 月 18 日', shift: '晚班', staff: '李娜', phone: '13700003333' },
{ id: 4, date: '11 月 19 日', shift: '早班', staff: '赵敏', phone: '13600004444' },
{ id: 5, date: '11 月 19 日', shift: '晚班', staff: '刘静', phone: '13500005555' },
{ id: 6, date: '11 月 20 日', shift: '休息日,不排班', staff: '', phone: '' }
]
// 每一行的“日期”占几行:同一天的第一行占这一天的行数,后面几行是 0(被合并掉)
const dateRowspans = data.map((row, index) => {
if (index > 0 && data[index - 1].date === row.date) return 0
let count = 1
while (data[index + count]?.date === row.date) count++
return count
})
const spanMethod = ({ row, rowIndex, columnIndex }: TableSpanMethodParams) => {
if (columnIndex === 0) {
const rowspan = dateRowspans[rowIndex]
return [rowspan, rowspan > 0 ? 1 : 0] as [number, number]
}
// 休息日:“班次”占 3 列,后面两列被合并掉
if (row.staff === '') {
return columnIndex === 1 ? { rowspan: 1, colspan: 3 } : { rowspan: 0, colspan: 0 }
}
}
</script>
<template>
<HuiTable :data="data" :columns="columns" :span-method="spanMethod" border />
</template>
多级表头
列配置里写 children 就成了分组列,表头按层级自动算出每个单元格横跨几行几列。分组列只是表头上的一格,不对应数据:它的 prop 只用来区分列,起一个不重复的名字即可;表体、插槽、formatter、排序都按最下面一层的列(叶子列)来。分组单元格没写 align 时居中。
分组列设 fixed 时,它下面的列都跟着固定。下面“姓名”所在的分组固定在左边,“操作”固定在右边,“年龄”可以排序:
<script setup lang="ts">
import { HuiButton, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{
prop: 'person',
label: '员工',
fixed: 'left',
children: [
{ prop: 'name', label: '姓名', width: 100 },
{ prop: 'age', label: '年龄', width: 90, align: 'right', sortable: true }
]
},
{
prop: 'job',
label: '岗位信息',
children: [
{ prop: 'dept', label: '部门', width: 140 },
{ prop: 'position', label: '职位', width: 140 }
]
},
{
prop: 'contact',
label: '联系方式',
children: [
{ prop: 'phone', label: '电话', width: 160 },
{
prop: 'address',
label: '地址',
children: [
{ prop: 'city', label: '城市', width: 100 },
{ prop: 'street', label: '详细地址', width: 260 }
]
}
]
},
{ prop: 'action', label: '操作', width: 100, fixed: 'right' }
]
const data = [
{
id: 1,
name: '张伟',
age: 32,
dept: '研发中心',
position: '前端工程师',
phone: '13800001111',
city: '北京',
street: '朝阳区建国路 88 号'
},
{
id: 2,
name: '王芳',
age: 28,
dept: '财务部',
position: '会计',
phone: '13900002222',
city: '上海',
street: '浦东新区世纪大道 100 号'
},
{
id: 3,
name: '李娜',
age: 35,
dept: '市场部',
position: '市场经理',
phone: '13700003333',
city: '广州',
street: '天河区天河路 385 号'
}
]
</script>
<template>
<div style="max-width: 800px">
<HuiTable :data="data" :columns="columns" border>
<template #action>
<HuiButton size="small" type="primary" variant="link">编辑</HuiButton>
</template>
</HuiTable>
</div>
</template>
拖动调整列宽
带边框(border)时,鼠标移到表头单元格的右边缘会出现一条主色的线,按住拖动可以改这一列的宽度,松开后触发 column-resize,参数是列配置、新宽度和原来的宽度(px)。把手也能用 Tab 聚焦,按左、右方向键每次调整 10px。拖分组表头的右边缘调的是它最右边的那一列。
列配置里 resizable: false 的列不能拖动,minWidth 是拖动时的最小宽度(默认 40px)。建议留一列不设宽度:表格总是撑满容器,其他列都设了宽度时,多出来或不够的宽度会按比例分到每一列,拖动的列不会正好跟着鼠标走。下面“操作”列不能拖,“姓名”列最窄 80px,“地址”列不设宽度:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 120, minWidth: 80 },
{ prop: 'phone', label: '电话', width: 160 },
{ prop: 'address', label: '地址' },
{ prop: 'action', label: '操作', width: 100, resizable: false }
]
const data = [
{ id: 1, name: '张伟', phone: '13800001111', address: '北京市朝阳区建国路 88 号' },
{ id: 2, name: '王芳', phone: '13900002222', address: '上海市浦东新区世纪大道 100 号' },
{ id: 3, name: '李娜', phone: '13700003333', address: '广州市天河区天河路 385 号' }
]
const resizeText = ref('')
const handleColumnResize = (column: TableColumnConfig, width: number, oldWidth: number) => {
resizeText.value = `column-resize:“${column.label}”从 ${oldWidth}px 调到了 ${width}px`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="data" :columns="columns" border @column-resize="handleColumnResize">
<template #action>
<HuiButton size="small" type="primary" variant="link">编辑</HuiButton>
</template>
</HuiTable>
<p>{{ resizeText || '拖动表头单元格之间的分隔线试试' }}</p>
</HuiSpace>
</template>
超长省略
默认单元格内容放不下时换行。列上设 showOverflowTooltip: true 后,这一列只显示一行、放不下的部分显示省略号,鼠标移上去用提示显示完整内容(放得下时不提示)。表格上设 show-overflow-tooltip 对所有列生效,列上写 showOverflowTooltip: false 可以单独关掉。写了插槽的列也能省略,提示里显示插槽的文字。
下面第一张表只有“地址”列省略;第二张表所有列都省略,但“备注”列关掉了,照常换行:
<script setup lang="ts">
import { HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '客户', width: 160 },
{ prop: 'address', label: '地址', width: 240, showOverflowTooltip: true },
{ prop: 'remark', label: '备注' }
]
const tableColumns: TableColumnConfig[] = [
{ prop: 'name', label: '客户', width: 160 },
{ prop: 'address', label: '地址', width: 240 },
{ prop: 'remark', label: '备注', showOverflowTooltip: false }
]
const data = [
{
id: 1,
name: '北京星辰科技有限公司',
address: '北京市朝阳区建国路 88 号现代城 SOHO 写字楼 B 座 2201 室',
remark: '每月 5 日前开具上月发票,邮寄到财务部王芳收。'
},
{
id: 2,
name: '上海浦江国际贸易有限责任公司',
address: '上海市浦东新区世纪大道 100 号',
remark: '只接受对公转账。'
},
{
id: 3,
name: '广州云帆物流',
address: '广州市天河区天河路 385 号太古汇一座 32 楼',
remark: '收货时间:工作日 9:00—18:00,周末不收货,请提前电话联系仓库。'
}
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="data" :columns="columns" border />
<HuiTable :data="data" :columns="tableColumns" show-overflow-tooltip border />
</HuiSpace>
</template>
配合分页
表格本身不分页。把当前页的数据算出来传给 data,分页用 HuiPagination。
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiPagination, HuiSpace, HuiTable } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const columns: TableColumnConfig[] = [
{ prop: 'id', label: 'ID', width: 80 },
{ prop: 'name', label: '姓名', width: 120 },
{ prop: 'address', label: '地址' }
]
const surnames = ['张', '王', '李', '赵', '刘', '陈']
const givenNames = ['伟', '芳', '娜', '敏', '静']
const cities = ['北京市', '上海市', '广州市', '深圳市', '杭州市']
const all = Array.from({ length: 30 }, (_, index) => ({
id: index + 1,
name: `${surnames[index % 6]}${givenNames[index % 5]}`,
address: cities[index % 5]
}))
const currentPage = ref(1)
const pageSize = ref(10)
const pageData = computed(() => {
const start = (currentPage.value - 1) * pageSize.value
return all.slice(start, start + pageSize.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiTable :data="pageData" :columns="columns" stripe />
<HuiPagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="all.length"
layout="total, sizes, prev, pager, next"
/>
</HuiSpace>
</template>
加载状态与自定义表头
loading 的遮罩只覆盖可见表体,表头、合计行和滚动条保持可见、可操作;滚动时遮罩位置不随表格内容移动。列和分组都可通过 header-{prop} 自定义表头,排序仍可使用。v-loading 指令仍可覆盖整个表格,两者按需要选择。
遮罩默认穿透鼠标命中,滚轮、触摸及惯性滚动由滚动容器原生处理。加载中的 tbody 使用 inert,阻止表体点击、键盘聚焦、选择与读屏访问;结束加载后恢复。表头、合计和加载提示不在 inert 区域。自定义 loading 插槽只在实际内容盒范围恢复交互,其他遮罩区域仍可滚动。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiTable, HuiSwitch, HuiSpace } from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const loading = ref(false)
const columns: TableColumnConfig[] = [
{
prop: 'profile',
label: '资料',
children: [
{ prop: 'name', label: '姓名', sortable: true, fixed: 'left', width: 160 },
{ prop: 'age', label: '年龄', sortable: true }
]
}
]
const data = [
{ id: 1, name: '张三', age: 28 },
{ id: 2, name: '李四', age: 32 }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace align="center"><span>加载中</span><HuiSwitch v-model="loading" /></HuiSpace>
<HuiTable
:data="data"
:columns="columns"
:loading="loading"
loading-text="正在查询资料"
:height="220"
show-summary
row-key="id"
>
<template #header-profile="{ column }"
><strong>{{ column.label }}分组</strong></template
>
<template #header-name="{ column }"
><span>{{ column.label }}(可排序)</span></template
>
</HuiTable>
</HuiSpace>
</template>
加载且没有数据时,表体预留约三行高度,不渲染空文字或 empty 插槽;加载结束后再显示空状态。loading-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: '姓名' },
{ prop: 'amount', label: '金额' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>加载中</span><HuiSwitch v-model="loading" /></HuiSpace>
<div>
<p>默认语言提示</p>
<HuiTable :data="[]" :columns="columns" :loading="loading" empty-text="没有符合条件的记录" />
</div>
<div>
<p>loading-text="",只显示图标</p>
<HuiTable :data="[]" :columns="columns" :loading="loading" loading-text="" />
</div>
</HuiSpace>
</template>
loading 插槽替换默认图标和文字,内容显示在表体遮罩中央,支持业务按钮;不要自行将包装铺满整个遮罩,以免阻挡原生滚动。下面关闭加载后才会渲染 empty 插槽。
<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: '任务' },
{ prop: 'progress', label: '进度' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>加载中</span><HuiSwitch v-model="loading" /></HuiSpace>
<HuiTable :data="[]" :columns="columns" :loading="loading" border>
<template #loading>
<HuiSpace><HuiIcon name="loading" spin /><span>正在准备任务列表…</span></HuiSpace>
</template>
<template #empty><span>当前没有待办任务</span></template>
</HuiTable>
</HuiSpace>
</template>
反转后端分支标记
后端仍返回 hasChildren 时,通过 isLeaf 读取函数反转语义;无需改动业务数据。
<script setup lang="ts">
import { HuiTable } from '@nscode/handy-ui'
import type { TableLoadMethod, TableTreeProps } from '@nscode/handy-ui'
const data = [
{ id: 1, name: '分支', hasChildren: true },
{ id: '1', name: '叶子', hasChildren: false }
]
const treeProps: TableTreeProps = { isLeaf: (row) => !row.hasChildren }
const load: TableLoadMethod = async () => [{ id: 11, name: '子行', hasChildren: false }]
</script>
<template>
<HuiTable
:data="data"
:columns="[{ prop: 'name', label: '名称' }]"
:tree-props="treeProps"
:load="load"
selectable
/>
</template>
与外层表单的边界
表格自有勾选是浏览操作,不继承外层 Form 的禁用、只读或校验,也不抢占 FormItem 标签。单元格、展开、空状态和加载插槽仍保留使用者的表单上下文;本例插槽输入框保持禁用,标签关联它。表格和复选框仍按 Table 自己的尺寸显示。
<script setup lang="ts">
import { HuiForm, HuiFormItem, HuiInput, HuiTable } from '@nscode/handy-ui'
const boundaryData = [{ id: 1, name: '业务编辑值' }]
</script>
<template>
<HuiForm disabled size="large">
<HuiFormItem label="业务字段">
<HuiTable
:data="boundaryData"
:columns="[{ prop: 'name', label: '名称' }]"
selectable
size="small"
>
<template #name="{ row }"><HuiInput :model-value="row.name" /></template>
</HuiTable>
</HuiFormItem>
</HuiForm>
</template>
虚拟滚动:1万行定位
固定行高窗口内按严格 key 定位;四种对齐避开表头和合计。smooth 交给浏览器滚动,方法结果表示目标已找到并发起滚动,不表示动画结束。全选仍包含窗口外记录。
start 贴表体视口顶部,center 居中,end 贴底部;默认 nearest 保留已完整可见的行,否则按最近边缘滚动。首尾位置受实际滚动范围限制,两种渲染模式使用同一套对齐含义,横向滚动位置保持不变。
<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: `记录 ${index + 1}`,
amount: index + 1
}))
const columns: TableColumnConfig[] = [
{ prop: 'id', label: '编号', width: 100 },
{ prop: 'name', label: '名称', width: 200 },
{ prop: 'amount', label: '金额', width: 140, align: 'right' }
]
const selected = ref<(string | number)[]>([])
const smooth = ref(false)
const result = ref('尚未定位')
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 ? '已发起定位' : '未找到或视口不可用'}`
}
</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')">最后一行</HuiButton>
<HuiButton @click="locate('5000')">字符串 '5000'(不存在)</HuiButton>
</HuiSpace>
<HuiSpace
><span>smooth</span><HuiSwitch v-model="smooth" /><span>{{ result }}</span></HuiSpace
>
<span>共10000行,已选{{ selected.length }}行</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>
虚拟滚动:固定列与合计
保留同一张原生表的左右固定列、吸顶表头和吸底合计。切换虚拟开关后,同一个 scrollToRow 方法也能定位普通模式;方法不改变选择,不自动回顶。明确列宽能避免 auto 随可见窗口变宽或变窄。
<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('尚未定位')
const rows = Array.from({ length: 200 }, (_, index) => ({
id: index + 1,
name: `客户 ${index + 1}`,
description: `记录 ${index + 1} 的详细说明`,
amount: index + 1
}))
const columns: TableColumnConfig[] = [
{ prop: 'id', label: '编号', width: 100, fixed: 'left' },
{ prop: 'name', label: '名称', width: 180 },
{ prop: 'description', label: '详细说明', width: 600 },
{ prop: 'amount', label: '金额', 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)"
>定位150</HuiButton
><HuiButton @click="locate(1)">定位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>
虚拟滚动:树形与未展开节点
树形按展开后的逻辑行虚拟化。scrollToRow 不会自动展开祖先:未展开子节点返回 false;先展开后可定位。勾选全部仍按所有已加载节点计算,收起分支不会丢选择。
<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('尚未定位')
const rows = Array.from({ length: 50 }, (_, group) => ({
id: `group-${group}`,
name: `分组 ${group + 1}`,
children: Array.from({ length: 200 }, (_, child) => ({
id: `group-${group}-${child}`,
name: `节点 ${group + 1}-${child + 1}`
}))
}))
const columns: TableColumnConfig[] = [{ prop: 'name', label: '节点', 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 = '已展开全部分组'
}
const collapse = () => {
table.value?.collapseAll()
result.value = '已收起全部分组'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><HuiButton @click="locate">定位子节点</HuiButton
><HuiButton @click="expand">先展开全部</HuiButton
><HuiButton @click="collapse">收起全部</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>
虚拟滚动限制
- virtualScroll 必须配合有效 height 或 maxHeight;百分比高度要求父容器有确定高度。无有效约束时保持完整渲染,并在开发环境提示。
- itemSize 仅为有限正数的固定像素行高,不接受函数;省略或无效时挂载后按布局坐标测首个真实数据行。隐藏零尺寸不覆盖有效测量,size/border/itemSize 改变后重新测量。
- 数据格单行显示,超过固定行高的内容会被裁剪;离屏插槽组件卸载,编辑状态应保存在业务数据中。
- 详情展开不支持:隐藏详情展开列、不渲染 expand 插槽,并发开发警告;树节点仍能正常展开。
- rowspan 大于1时降为1,原纵向覆盖格恢复独立单元格;横向 colspan 与同排覆盖格仍保持合并,并发开发警告。
- auto 保持原布局,列宽可能随可见窗口变化;此组合会发开发警告。需要稳定固定列偏移时建议明确列宽。
- 每种不支持组合在一次启用期间只警告一次,滚动和无关父重绘不重复;退出该组合后重新启用会再次提示。
- 原生表格、吸顶表头、合计和全数据选择保留;ARIA下标包含逻辑行、表头与合计。
- scrollToRow 严格区分数字与字符串 key。不存在、收起分支中的节点、不可用视口、SSR及卸载后调用返回 false;不会自动展开、改变选择或抢焦点。smooth 由浏览器执行,布尔返回值不表示动画完成。
表头筛选
列设置 filterOptions 后显示筛选按钮。默认多选,先编辑草稿、点击确定提交;filterMultiple: false 单选即选即提交。关闭或按 Esc 丢弃草稿,重开从实际筛选值开始;父筛选、列身份或候选项变化使旧草稿和插槽回调失效。
filterMethod(value, row, column, cellValue) 决定本地匹配,第四参来自路径/accessor共用原始取值。同行多个值取“或”,不同列取“且”;不写方法则只发事件,数据由业务远程查询。filterValue 未传时内部保存,传入即受控(含undefined),父拒绝时保持原结果。事件先 update:filterValue 再 filter-change,参数都是新筛选值的独立快照。
<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('尚未筛选')
const rows = [
{ id: 1, name: '张伟', state: { code: 'active' }, amount: 30 },
{ id: 2, name: '李娜', state: { code: 'paused' }, amount: 50 },
{ id: 3, name: '王芳', state: { code: 'active' }, amount: 70 }
]
const options = [
{ label: '有效', value: 'active' },
{ label: '暂停', value: 'paused' }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名' },
{
prop: 'state.code',
label: '状态(多选)',
filterOptions: options,
filterMethod: (value, _row, _column, cellValue) => value === cellValue
},
{
prop: 'amount',
label: '金额(单选)',
sortable: true,
filterMultiple: false,
filterOptions: [
{ label: '至少50', value: 50 },
{ label: '至少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'])">重置状态列</HuiButton>
<HuiButton @click="table?.clearFilter()">重置全部筛选</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>
合计和自定义 summaryMethod 接收筛选后的根行;排序和 spanMethod 的行号跟随筛选结果。筛掉的勾选及当前行 key 保留,全选只作用筛选后逻辑行。树默认只筛根行,列加 filterChildren: true 后递归筛子行,保留命中后代的祖先,不修改原始树;尚未加载的后代不预先参与筛选。
远程筛选与自定义面板
以下列省略 filterMethod,仅把筛选条件交给远程查询。示例用同步数组模拟返回结果。filter-<prop> 插槽提供 value/setValue/confirm/reset/close,其中value是本轮草稿;reset 清空并提交本列,close 丢弃草稿。异步回调仅对当前打开会话有效,关闭重开或卸载后旧回调不操作新面板。
<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: '甲', status: 'open' },
{ id: 2, name: '乙', status: 'closed' }
]
const rows = ref(source)
const filters = ref<TableFilterValue>({})
const requests = ref(0)
const columns = [
{ prop: 'name', label: '姓名' },
{ prop: 'status', label: '远程状态', 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 }}</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>草稿:{{ value.join(', ') || '无' }}</span>
<HuiButton @click="setValue(['open'])">仅未关闭</HuiButton>
<HuiSpace>
<HuiButton type="primary" @click="confirm">应用</HuiButton>
<HuiButton @click="reset">重置</HuiButton>
<HuiButton @click="close">取消</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
</HuiTable>
</HuiSpace>
</template>
勾选与排序的状态归属
不传selectedKeys或sortState时内部保存,仅监听update不变成受控。属性存在即受控,显式undefined分别表示空勾选/无排序,sortState=undefined也优先于defaultSort。父值决定显示,受控请求不覆盖内部草稿;移除属性恢复此前内部值,控制模式切换在开发环境提示。保留同一同步批次累积勾选请求,下一批被拒绝的候选仍回到父值。数据清理只请求update:selectedKeys,不发用户selection-change。
当前行高亮与受控请求
highlight-current 开启点行高亮,current-key 按 row-key 保存当前行。它与复选框的 selectedKeys 独立:点行不改变勾选,勾选和展开按钮也不改变当前行。当前行有左侧主色标记,并通过 aria-current 标识。
未传 current-key 时内部保存;传入即受控,包含显式 undefined,null 表示清空。父组件拒绝回填时保留原高亮。点行和 setCurrentRow(row) 先发 update:currentKey,再发 current-change(key, { row, previousKey, previousRow });重复选择实际当前行不发事件。上下文描述当次请求,不会因为父组件同步改写值而变成另一行。
<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('点击一行观察当前行请求')
const rows = [
{ id: 0, name: '张伟', dept: '研发部' },
{ id: 2, name: '李娜', dept: '财务部' }
]
const columns = [
{ prop: 'name', label: '姓名' },
{ prop: 'dept', label: '部门' }
]
const updateCurrent = (key: string | number | null) => {
if (acceptRequest.value) currentKey.value = key
}
const onCurrent = (key: string | number | null, context: TableCurrentChangeContext) => {
status.value = `请求 ${key ?? '无'},上一行 ${context.previousRow?.name ?? '无'},本次行 ${context.row?.name ?? '无'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="acceptRequest" active-text="接受更新" inactive-text="拒绝更新" />
<HuiButton @click="table?.setCurrentRow(rows[1])">方法设置第二行</HuiButton>
<HuiButton @click="table?.setCurrentRow(null)">清空当前行</HuiButton>
<HuiButton @click="currentKey = 0">外部指定第一行</HuiButton>
</HuiSpace>
<span
>实际当前 key:{{ currentKey ?? '无' }};勾选 key:{{ selectedKeys.join(', ') || '无' }}</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>
同 key 的行重建或重排会保留当前行;树形子行折叠后保存 key,重新展开恢复高亮。数据中移除当前 key 时只请求 update:currentKey(null),不发用户 current-change;受控时仍由父组件决定。setCurrentRow 接受当前数据中同 key 的行副本,事件使用实际行;未知行不操作,不传参数或传 null 清空。仅设置当前行不会自动滚动,可配合 scrollToRow(key) 定位。
明细表编辑与校验
单元格插槽中组合Input、InputNumber、Select与EditableText,外层Form统一校验和只读。数据以稳定id标识;字段路径通过id回查model.rows原始下标,不能使用排序/筛选后的rowIndex。备注在行内确认后写入明细,整表保存仅记录本地快照,便于观察后续编辑不会修改已保存结果。
移除前确认当前明细及其输入,取消或关闭不改变数据;确认期间集合被替换、增删或重排时放弃旧操作,只读时所有写入入口均关闭。该示例展示组合用法,表格本身不接管编辑状态。
<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('可排序后继续编辑;保存时校验全部明细')
const saved = ref<Detail[]>([])
let nextId = 3
let alive = true
onBeforeUnmount(() => {
alive = false
})
const model = reactive<{ rows: Detail[] }>({
rows: [
{ id: 1, name: '笔记本', unit: '本', quantity: 2, price: 6, note: '' },
{ id: 2, name: '水笔', unit: '支', quantity: 3, price: 2, note: '' }
]
})
let removalRevision = 0
watch([() => model.rows, readonly, saving], () => removalRevision++, {
deep: true,
flush: 'sync'
})
const units = [
{ label: '本', value: '本' },
{ label: '支', value: '支' },
{ label: '盒', value: '盒' }
]
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '物料名称', width: 180, sortable: true },
{ prop: 'unit', label: '单位', width: 100 },
{ prop: 'quantity', label: '数量', width: 160, sortable: true },
{ prop: 'price', label: '单价', width: 160 },
{
prop: 'amount',
label: '金额',
width: 100,
accessor: (row) => Number(row.quantity ?? 0) * Number(row.price ?? 0),
formatter: (_row, _column, value) => Number(value).toFixed(2)
},
{ prop: 'note', label: '备注', width: 200 },
{ prop: 'actions', label: '操作', width: 90 }
]
const total = computed(() =>
model.rows
.reduce((sum, row) => sum + Number(row.quantity ?? 0) * Number(row.price ?? 0), 0)
.toFixed(2)
)
// 校验路径取模型原始位置;排序后的rowIndex只表示当前显示顺序。
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 = '已添加待填写明细'
}
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(
`移除明细“${row.name || '未命名物料'}”及其当前输入?其他明细不受影响。`,
'移除明细',
{
confirmButtonText: '移除',
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 = '明细已变化,本次移除取消,请重新操作'
return
}
const index = collection.indexOf(row)
if (index < 0) return
collection.splice(index, 1)
status.value = '已移除当前明细'
} catch (action) {
if (alive)
status.value =
action === 'cancel' || action === 'close'
? '已取消移除,明细保留'
: '移除未完成,明细保留'
} finally {
if (alive) removing.value = null
}
}
const save = async () => {
if (readonly.value || saving.value || removing.value !== null) return
if (!model.rows.length) {
status.value = '请至少添加一条明细'
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 = '明细已变化,请重新保存'
return
}
if (!result?.valid) {
status.value = '请修正标红的明细后再保存'
return
}
saved.value = collection.map((row) => ({ ...row }))
status.value = `校验通过,已保存${saved.value.length}条明细快照`
} 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"
>添加明细</HuiButton
>
<HuiButton
class="detail-save"
type="primary"
:loading="saving"
:disabled="readonly || removing !== null"
@click="save"
>校验并保存</HuiButton
>
<HuiSwitch v-model="readonly" active-text="只读" />
<span>金额合计:{{ 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: '请填写物料名称' }]"
>
<HuiInput v-model="row.name" :aria-label="`物料名称-${row.id}`" />
</HuiFormItem>
</template>
<template #unit="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'unit')"
:rules="[{ required: true, message: '请选择单位' }]"
>
<HuiSelect v-model="row.unit" :options="units" :aria-label="`单位-${row.id}`" />
</HuiFormItem>
</template>
<template #quantity="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'quantity')"
:rules="[{ required: true, type: 'number', min: 1, message: '数量至少为1' }]"
>
<HuiInputNumber v-model="row.quantity" :min="1" :aria-label="`数量-${row.id}`" />
</HuiFormItem>
</template>
<template #price="{ row }">
<HuiFormItem
:prop="pathFor(row.id, 'price')"
:rules="[
{ required: true, type: 'number', min: 0, message: '单价不能为空且不能小于0' }
]"
>
<HuiInputNumber
v-model="row.price"
:min="0"
:precision="2"
:aria-label="`单价-${row.id}`"
/>
</HuiFormItem>
</template>
<template #note="{ row }">
<HuiEditableText
v-model="row.note"
trigger="click"
show-actions
empty-text="点击编辑备注"
:disabled="readonly || saving"
/>
</template>
<template #actions="{ row }">
<HuiButton
type="danger"
variant="text"
:aria-label="`移除明细-${row.id}`"
:disabled="readonly || saving || removing !== null"
@click="remove(row)"
>移除</HuiButton
>
</template>
</HuiTable>
</HuiForm>
<span class="detail-status" role="status">{{ status }}</span>
<code class="detail-saved">已保存快照:{{ JSON.stringify(saved) }}</code>
</HuiSpace>
</template>
懒加载失败与重试
加载函数同步抛错或 Promise 拒绝时触发 load-error,上下文包含原行、严格类型的 key 和原始异常。失败后释放加载状态、保持收起,可以再点展开箭头,或调用 toggleRowExpansion(row, true) 重试。下例首次失败、第二次成功,错误和次数显示在页面上。
<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: '待加载目录', isLeaf: false }]
const columns: TableColumnConfig[] = [{ prop: 'name', label: '名称' }]
const attempts = ref(0)
const errorText = ref('')
const status = ref('点击目录展开按钮,第一次加载将失败。')
const load: TableLoadMethod = async () => {
errorText.value = ''
attempts.value += 1
if (attempts.value === 1) throw new Error('模拟连接失败')
status.value = '重试成功,子行已展开。'
return [{ id: 2, name: '重试后加载的文件', isLeaf: true }]
}
const handleLoadError = ({ row, key, error }: TableLoadErrorContext) => {
errorText.value = error instanceof Error ? error.message : String(error)
status.value = `${row.name}(key=${key})加载失败:${errorText.value}。点击箭头或下方按钮重试。`
}
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">重试加载目录</HuiButton>
<span class="load-status" role="status">{{ status }} 请求次数:{{ attempts }}</span>
</HuiSpace>
</template>
逐行禁选与单选
用 rowSelectable(row) 决定哪些行可以勾选;点击、全选及 toggleRowSelection 均受限制。已由外部选中而后禁用的行保持选中,全选状态只计算筛选后可选的全部逻辑行,包含收起的树节点和虚拟窗口外行;clearSelection() 仍可清除全部选择。
selectable 开启时,selectionMode="single" 使用同组单选按钮且不显示全选框。重新点击当前项不取消;公开方法传 false 或调用 clearSelection() 可清空。外部多 key 只取第一项生效并提议清理,父拒绝不会被反写;单选与当前行高亮独立。
<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('系统账号始终禁选;可切换单选和多选。')
const data = [
{ id: 0, name: '系统账号', locked: true },
{ id: 1, name: '普通账号甲', locked: false },
{ id: 2, name: '普通账号乙', locked: false }
]
const columns: TableColumnConfig[] = [{ prop: 'name', label: '账号' }]
const rowSelectable = (row: TableRowData) => !row.locked && !(row.id === 2 && lockSecond.value)
const update = (next: (string | number)[]) => {
requests.value += 1
message.value = `请求 key:${JSON.stringify(next)};父${accept.value ? '接受' : '拒绝'}。`
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 = '系统账号被禁选,公开方法也未发出更新。'
}
</script>
<template>
<HuiSpace class="table-selection-demo" direction="vertical" fill>
<HuiSpace wrap>
<HuiButton class="selection-multiple" @click="mode = 'multiple'">多选</HuiButton>
<HuiButton class="selection-single" @click="mode = 'single'">单选</HuiButton>
<HuiSwitch v-model="accept" active-text="接受请求" inactive-text="拒绝请求" />
<HuiSwitch v-model="lockSecond" active-text="禁用账号乙" />
</HuiSpace>
<HuiSpace wrap>
<HuiButton class="selection-system" @click="selectSystem">方法尝试选择系统账号</HuiButton>
<HuiButton :disabled="mode === 'single'" @click="table?.toggleAllSelection()"
>切换可选行全选</HuiButton
>
<HuiButton @click="table?.clearSelection()">清除选择</HuiButton>
<HuiButton @click="keys = [0]">外部指定系统账号</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 }};父 key:{{ JSON.stringify(keys) }};有效选择:{{
table?.selection.map((row) => row.name).join('、') || '无'
}};请求次数:{{ requests }}</span
>
</HuiSpace>
</template>
自动布局与主题间距
自动布局的表头、数据和合计内容盒使用同一套宽度换算:列约束扣除当前尺寸的左右内边距,以及实际存在的右边框。large/default/small仍分别使用 --hui-spacing-4/3/2,边框宽度仍来自 --hui-border-width;末列没有右边框,不多扣一条线。
下例在祖先统一设置主题间距为24/20/12px、边框为2px。切换尺寸和边框后,内容盒会同步调整,长文字仍保持单行省略;auto布局的列约束及容器最小宽度规则保持原样。
<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: '这是用于验证内容盒宽度与省略的较长名称', amount: 120 },
{ id: 2, name: '另一条用于验证对齐的较长名称', amount: 240 }
]
const variableColumns: TableColumnConfig[] = [
{ prop: 'name', label: '名称(180px)', width: 180 },
{ prop: 'amount', label: '数量(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"
>边框:{{ variableBorder ? '开' : '关' }}</HuiButton
>
</HuiSpace>
<p class="table-variables-result">
当前尺寸:{{ variableSize }};边框:{{ variableBorder ? '开' : '关' }}
</p>
<HuiTable
:data="variableRows"
:columns="variableColumns"
:size="variableSize"
:border="variableBorder"
table-layout="auto"
show-summary
/>
</div>
</template>
旧名 --hui-table-auto-cell-padding 和 --hui-table-auto-cell-border 是内容限宽的内部换算量,已收为私有变量,不留旧名读取。业务通过尺寸、边框属性及主题变量调整实际外观,不直接设置这些中间量;每个auto表格重置自己的私有值,嵌套表格仍按各自布局与尺寸工作。
撑满剩余视口高度
开启 fillViewport 后,从表格顶部量到布局视口底部。fillOffset 预留底部距离,fillMinHeight 默认 200px,计算的是包含表头与合计的总高度。此时忽略 height,maxHeight 仍是独立上限,可以小于最小高度;关闭撑满恢复原 height。
窗口缩放、表格自身和 body 尺寸通知按帧合并。只改变位置、未产生尺寸通知时调用 updateLayout()。SSR 不猜测视口高度,也不回退到已忽略的 height,保留 maxHeight。fillViewport 也可作为虚拟滚动的高度条件。
<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('尚未手动刷新')
const rows = Array.from({ length: 80 }, (_, id) => ({ id, name: `记录 ${id + 1}` }))
const columns = [{ prop: 'name', label: '名称' }]
const refresh = () => {
table.value?.updateLayout()
result.value = '已按当前位置刷新布局'
}
</script>
<template>
<HuiSpace direction="vertical" fill class="table-fill-demo">
<HuiSpace wrap>
<HuiSwitch
v-model="fill"
class="table-fill-toggle"
active-text="撑满开启"
inactive-text="撑满关闭"
/>
<HuiButton class="table-fill-query" @click="expanded = !expanded">切换上方查询区</HuiButton>
<HuiButton class="table-fill-offset" @click="offset = offset === 24 ? 80 : 24"
>底部预留:{{ offset }}px</HuiButton
>
<HuiButton class="table-fill-min" @click="minimum = minimum === 200 ? 300 : 200"
>最小高度:{{ minimum }}px</HuiButton
>
<HuiButton class="table-fill-refresh" @click="refresh">updateLayout()</HuiButton>
</HuiSpace>
<p v-if="expanded">
查询区展开后表格向下移动;窗口或页面尺寸通知会重新计算剩余高度。仅位置变化时,可手动刷新。
</p>
<p class="table-fill-result">
{{ result }};关闭撑满时恢复固定高度 240px,最大高度始终为 480px。
</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>
通用高度工具与父容器高度
useFillHeight(target, { offset, minHeight, enabled }) 返回只读 height 和立即重算的 update()。target 接受 ref/getter;三个选项接受值、ref 或 getter,默认分别为 0/200/true。无目标、关闭或 SSR 时 height 为 undefined,关闭及卸载清理监听。非有限数用默认值,负最小高度按零处理,负 offset 表示向下延伸。结果是目标外框总高度,不是表体高度;通用容器增加边框或内边距时自行配 box-sizing: border-box。
父容器已有确定高度时,可直接用 height="100%" 配合 flex 收缩。下面分别展示两种用法:
<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: `记录 ${id + 1}` }))
const columns = [{ prop: 'name', label: '名称' }]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="update">刷新通用容器高度</HuiButton>
<div
ref="target"
:style="{
height: height === undefined ? undefined : `${height}px`,
maxHeight: '360px',
overflow: 'auto'
}"
>
<p v-for="line in 30" :key="line">通用滚动区第 {{ line }} 行</p>
</div>
<div style="display:flex;flex-direction:column;height:240px">
<p style="flex:none">父容器已有确定高度时,表格可直接使用 height="100%"。</p>
<HuiTable :data="rows" :columns="columns" height="100%" style="min-height:0" />
</div>
</HuiSpace>
</template>
逐行禁选
用 rowSelectable(row) 决定哪些行可以勾选;点击、全选及 toggleRowSelection 均受限制。已经选中而后禁用的行保持选中,全选状态只计算当前数据中可选的全部逻辑行,包含收起的树节点和虚拟窗口外行;clearSelection() 仍可清除全部选择。
公开方法按当前数据里的同 key 原行检查资格,传入旧副本不能放开禁选。父组件拒绝更新时保持实际选择;禁选条件变化后立即按最新结果判断。
<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('系统账号始终禁选;可切换父接受与临时禁选。')
const data = [
{ id: 0, name: '系统账号', locked: true },
{ id: 1, name: '普通账号甲', locked: false },
{ id: 2, name: '普通账号乙', locked: false }
]
const columns: TableColumnConfig[] = [{ prop: 'name', label: '账号' }]
const rowSelectable = (row: TableRowData) => !row.locked && !(row.id === 2 && lockSecond.value)
const update = (next: (string | number)[]) => {
requests.value += 1
message.value = `请求 key:${JSON.stringify(next)};父${accept.value ? '接受' : '拒绝'}。`
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 = '系统账号被禁选,公开方法也未发出更新。'
}
</script>
<template>
<HuiSpace class="table-selection-demo" direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="accept" active-text="接受请求" inactive-text="拒绝请求" />
<HuiSwitch v-model="lockSecond" active-text="禁用账号乙" />
</HuiSpace>
<HuiSpace wrap>
<HuiButton class="selection-system" @click="selectSystem">方法尝试选择系统账号</HuiButton>
<HuiButton @click="table?.toggleAllSelection()">切换可选行全选</HuiButton>
<HuiButton @click="table?.clearSelection()">清除选择</HuiButton>
<HuiButton @click="keys = [0]">外部指定系统账号</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"
>父 key:{{ JSON.stringify(keys) }};有效选择:{{
table?.selection.map((row) => row.name).join('、') || '无'
}};请求次数:{{ requests }}</span
>
</HuiSpace>
</template>
性能
大数据量时,把 columns 放在 setup 里定义,避免在模板里内联创建列配置。表格会复用内容不变的排序与筛选规格,路径取值和当前语言的字符串比较器也会复用;本地排序先读取每行的值,再进行比较。
rowKey 函数可内联,父组件重绘时不会因为函数引用变化重建行索引。若更换 rowKey 的取值算法,请同时更换表格的 key,让表格重新建立标识和选择状态。
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| data | TableRowData[] | [] | 行数据 |
| columns | TableColumnConfig[] | - | 列配置。不传或传空数组时按第一行数据的字段名生成列 |
| tableLayout | TableLayout | 'fixed' | fixed 按配置分列;auto 按内容分配、单行显示,内容超出 maxWidth 时省略 |
| stripe | boolean | false | 是否显示斑马纹 |
| border | boolean | false | 是否显示外边框和单元格之间的竖线。带边框时可以拖动表头调整列宽 |
| size | 'large' | 'default' | 'small' | - | 尺寸:单元格内边距 16 / 12 / 8px,字号 14 / 14 / 12px。不写时跟随 ConfigProvider,都没有时是 'default' |
| height | string | number | - | 表格高度,超出时表体滚动、表头固定。数字的单位是 px |
| maxHeight | string | number | - | 表格最大高度,超出后才滚动。数字的单位是 px |
| fillViewport | boolean | false | 撑满剩余视口高度,忽略 height,保留 maxHeight |
| fillOffset | number | 0 | 撑满时底部预留距离,单位 px |
| fillMinHeight | number | 200 | 撑满时最小总高度,单位 px;maxHeight 仍优先约束 |
| virtualScroll | boolean | false | 基础虚拟滚动,需有效 height、maxHeight 或 fillViewport,固定行高。 |
| itemSize | number | 首个数据行实测 | 固定行高,单位px,仅有限正数;省略或无效时实测,不接受函数。 |
| rowKey | string | ((row: TableRowData) => string | number) | 'id' | 行的稳定唯一标识;数字回调保留数字 |
| highlightCurrent | boolean | false | 点击数据行设置当前行并高亮,与勾选独立 |
| currentKey / v-model:current-key | string | number | null | 内部 null | 属性存在即受控,含undefined;null清空 |
| filterValue / v-model:filter-value | TableFilterValue | 内部 {} | 各列筛选值;属性存在即受控(含undefined),未传内部保存 |
| emptyText | string | 随语言(中文:暂无数据) | 没有数据时显示的文字 |
| selectable | boolean | false | 是否在最左边显示复选框列 |
| rowSelectable | (row: TableRowData) => boolean | - | 返回 false 时禁止点击、全选与 toggleRowSelection;已经选中的禁用行保持原选择 |
| selectionMode | 'multiple' | 'single' | 'multiple' | selectable 开启时生效;single 使用单选按钮、不显示全选框,最多一项 |
| selectedKeys / v-model:selected-keys | (string | number)[] | 内部空数组 | 属性存在即受控(undefined为空),未传内部保存;回填决定显示 |
| reserveSelection | boolean | false | 跨页保留 key 和已见行;全选只作用当前页,必须有稳定唯一 rowKey |
| defaultSort | { prop: string; order: 'ascending' | 'descending' } | - | 一开始的排序,只在创建时读取一次 |
| sortState / v-model:sort-state | TableSortState | — | 属性存在即受控;undefined为无排序并压过defaultSort,未传内部保存 |
| showHeader | boolean | true | 是否显示表头 |
| rowClassName | string | ((row: TableRowData, rowIndex: number) => string) | - | 行的类名 |
| cellClassName | string | ((row: TableRowData, column: TableColumnConfig, rowIndex: number) => string) | - | 单元格的类名 |
| headerCellClassName | string | ((column: TableColumnConfig) => string) | - | 表头单元格的类名。多级表头的分组单元格也会调用 |
| treeProps | TableTreeProps | - | 树形数据的字段名,默认 { children: 'children', isLeaf: 'isLeaf' } |
| indent | number | 16 | 树形数据每一级缩进的宽度(px) |
| load | TableLoadMethod | - | 懒加载子行。isLeaf 为 false、还没有子行的行显示展开按钮,第一次展开时调用 |
| defaultExpandAll | boolean | false | 一开始展开所有树形节点和展开行,只在创建时读取一次(数据晚到也生效)。懒加载的行不会因此自动加载 |
| defaultExpandedKeys | (string | number)[] | - | 一开始展开的行(rowKey 的值),树形节点和展开行都适用,只在创建时读取一次 |
| expandable | boolean | false | 是否在左边显示展开列(在复选框列后面),点开后在这一行下面显示 expand 插槽 |
| accordion | boolean | false | 展开行同时只展开一行 |
| showSummary | boolean | false | 是否在表尾显示合计行 |
| summaryText | string | 随语言(中文:合计) | 合计行第一列的文字 |
| summaryMethod | TableSummaryMethod | - | 自定义合计行每一列的内容。不传时把每一列数字类型的值加起来 |
| spanMethod | TableSpanMethod | - | 合并单元格:按行、列返回 [rowspan, colspan] 或 { rowspan, colspan },返回 0 的单元格不渲染 |
| showOverflowTooltip | boolean | false | 所有列的单元格只显示一行,放不下时显示省略号、鼠标移上去显示完整内容。列上的 showOverflowTooltip 优先于这里的设置 |
| loading | boolean | false | 只遮表体,表头和合计保持可见;空数据加载时不显示空状态;仅加载中写 aria-busy=true |
| loadingText | string | 随语言(中文:加载中) | 默认加载图标下的提示文字,空字符串表示不显示文字 |
列配置 TableColumnConfig
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| prop | string | - | 必填。字段或嵌套路径,同名字面量键优先;同时是列和插槽标识(expand、empty、loading 除外)。同表不能重复 |
| accessor | (row: TableRowData) => unknown | - | 自定义原始取值,优先于prop;显示、formatter、默认排序和默认合计共用 |
| filterOptions | TableFilterOption[] | — | 筛选候选,空数组可搭配自定义筛选插槽 |
| filterMultiple | boolean | true | 多选草稿确认后提交;false为单选即时提交 |
| filterMethod | (value, row, column, cellValue) => boolean | — | 本地判断,第四参共用原值;不传则远程筛选 |
| filterChildren | boolean | false | 递归筛子行并保留命中后代的祖先 |
| label | string | - | 必填。表头文字,超出列宽时显示省略号 |
| width | string | number | - | 列宽,数字的单位是 px。不设时平分剩下的空间 |
| align | 'left' | 'center' | 'right' | 'left' | 表头和单元格的对齐方式。多级表头的分组单元格不写时居中 |
| sortable | boolean | 'custom' | false | true 由表格排序;'custom' 只触发 sort-change,顺序由使用方处理。分组列设了不生效 |
| sortMethod | (a: TableRowData, b: TableRowData, order: TableSortOrder) => number | — | 本地比较函数,仅 sortable=true 生效;降序时表格统一取反 |
| sortOrders | TableSortOrder[] | ['ascending', 'descending', null] | 表头的排序循环;单项固定顺序,空数组用默认值 |
| fixed | 'left' | 'right' | - | 横向滚动时固定在左边或右边。设在分组列上时,下面的列都跟着固定 |
| className | string | - | 加到这一列表头和单元格上的类名 |
| formatter | (row: TableRowData, column: TableColumnConfig, cellValue: unknown) => string | - | 返回单元格要显示的文字。这一列写了插槽时不生效 |
| children | TableColumnConfig[] | - | 下级列,用来做多级表头。有下级列的列只是表头上的分组,不对应数据 |
| resizable | boolean | true | 带边框时能不能拖动调整这一列的宽度 |
| minWidth | number | 拖动默认 40 | 拖动时的最小宽度(px);auto 且没有明确 width 时也作为内容布局的最小宽度 |
| maxWidth | number | string | - | 仅 auto 的最大内容宽度,数字单位 px;明确 width 或拖动后的宽度优先;原生布局可分配额外空白 |
| showOverflowTooltip | boolean | - | 单元格只显示一行,放不下时显示省略号,鼠标移上去显示完整内容。不写时跟随表格上的同名属性 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| select | (selection: TableRowData[], row: TableRowData) | 某一行的选中状态变化时触发(点复选框或调用 toggleRowSelection)。selection 是变化后选中的全部行,row 是这一行 |
| select-all | (selection: TableRowData[]) | 点表头的全选框或调用 toggleAllSelection 时触发 |
| update:selectedKeys | (selectedKeys: (string | number)[]) | 请求更新选中 key;数字保持数字,数据清理也会触发 |
| update:currentKey | (key: string | number | null) | 请求更新当前key;数据清理只发此事件 |
| update:filterValue | (value: TableFilterValue) | 请求新筛选值,受控时由父决定 |
| filter-change | (value: TableFilterValue) | 确认/重置/方法请求,紧跟update,独立快照 |
| current-change | (key: string | number | null, context: TableCurrentChangeContext) | 点行或显式方法改变当前key,先update后通知,第二参含当前行及previousKey/previousRow |
| selection-change | (selection: TableRowData[]) | 选择操作提议的新行数组;受控时仍使用提议值,数据清理仅请求 update:selectedKeys |
| update:sortState | (sortState: TableSortState) | 请求更新排序,用于 v-model:sort-state;表头操作及 sort()/clearSort() 都会触发 |
| sort-change | (sortState: TableSortState) | 用户操作表头排序时触发;sort()/clearSort() 和外部赋值不触发,order 是 ascending、descending 或 null |
| row-click | (row: TableRowData, column: TableColumnConfig, event: MouseEvent) | 点击某一行时触发,column 是点到的那一列。点复选框列、展开列和树形数据的展开按钮不触发 |
| row-dblclick | (row: TableRowData, column: TableColumnConfig, event: MouseEvent) | 双击数据单元格;选择列、展开列和表头不触发,不阻止默认行为或冒泡 |
| row-contextmenu | (row: TableRowData, column: TableColumnConfig, event: MouseEvent) | 右键数据单元格,范围同 row-dblclick;不阻止原生菜单或冒泡 |
| cell-click | (row: TableRowData, column: TableColumnConfig, cell: HTMLTableCellElement, event: MouseEvent) | 点击单元格时触发,cell 是这个单元格的 <td> 元素。点复选框列、展开列不触发 |
| expand-change | (row: TableRowData, expanded: boolean, expandedRows: TableRowData[]) | 展开行或树形节点展开、收起时触发。expandedRows 是变化后展开着的全部行。expandAll、collapseAll 不触发 |
| load-error | (context: TableLoadErrorContext) | 当前行懒加载抛错或拒绝后触发,包含原行、key 和原异常;过期、换行或卸载的请求不通知 |
| column-resize | (column: TableColumnConfig, width: number, oldWidth: number) | 拖动或用方向键调整列宽后触发,宽度的单位是 px。拖动时松开鼠标才触发 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
列的 prop | { row: TableRowData, column: TableColumnConfig, rowIndex: number } | 自定义这一列单元格的内容,插槽名就是列配置里的 prop。rowIndex 是排序、展开后看得见的行里的行号,从 0 开始 |
| expand | { row: TableRowData, rowIndex: number } | 展开行的内容,开了 expandable 才显示 |
| empty | - | 没有数据时显示的内容,写了以后不再显示 emptyText |
| loading | - | 自定义表体加载内容,替换默认加载图标和文字,仅 loading=true 时渲染 |
| header- | { column: TableColumnConfig } | 自定义列或分组列的表头,排序和调整列宽保持有效 |
filter-<prop> | TableFilterSlotProps | 自定义草稿面板,value/setValue/confirm/reset/close只作用当前打开会话 |
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| scrollToRow | (key: string | number, options?: TableScrollToRowOptions) | boolean | 定位可见逻辑行;默认 nearest/auto。未找到、收起分支、视口不可用、SSR或卸载后返回 false,不自动展开;true 表示已发起滚动 |
| toggleRowSelection | (row: TableRowData, selected?: boolean) | void | 切换某一行的选中状态。传了 selected 时直接设成选中或不选中 |
| toggleAllSelection | - | void | 已经全选时取消全选,否则全选(树形数据包括收起着的子行)。没有数据时不做任何事 |
| clearSelection | - | void | 清空选中的行 |
| setCurrentRow | (row?: TableRowData | null) | void | 按当前数据key设置;未知行不操作,不传或null清空,受控等待父回填 |
| clearFilter | (props?: string[]) | void | 清指定列或全部筛选,遵循受控update/通知规则 |
| toggleRowExpansion | (row: TableRowData, expanded?: boolean) | void | 切换某一行的展开状态,传了 expanded 时直接设成展开或收起。开了 expandable 时切换展开行,否则切换树形节点(懒加载的行会先加载) |
| expandAll | - | void | 展开所有树形节点和展开行。不加载懒加载的行;开了 accordion 时不展开展开行 |
| collapseAll | - | void | 收起所有树形节点和展开行 |
| sort | (prop: string, order: TableSortOrder) | void | 更新排序并发 update:sortState,不发 sort-change;受控时等待回填 |
| clearSort | — | void | 清除排序并发 update:sortState,不发 sort-change;远程查询需调用方自行触发 |
| updateLayout | - | void | 立即重算剩余高度和表格布局,卸载后无效 |
ref 上还有 selection(按所选 key 顺序找到的行,数组为冻结浅拷贝,行对象身份不变)和深只读的 sortState(当前排序)。未知 key 在取到数据之前不会出现在 selection 中。
类型
import type {
TableColumnConfig,
TableSortState,
TableSortOrder,
TableSize,
TableAlign,
TableLayout,
TableProps,
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 TableColumnConfig {
/** 字段或嵌套路径,同名字面量键优先;同时作为列和插槽标识。 */
prop: string
/** 自定义原始取值,优先于prop。 */
accessor?: (row: TableRowData) => unknown
/** 表头文字 */
label: string
/** 列宽,数字的单位是 px */
width?: string | number
/** 表头和单元格的对齐方式 */
align?: TableAlign
/** `true` 由表格排序;`'custom'` 只触发 sort-change,顺序由使用方处理 */
sortable?: boolean | 'custom'
sortMethod?: (a: TableRowData, b: TableRowData, order: TableSortOrder) => number
sortOrders?: TableSortOrder[]
/** 横向滚动时固定在左边或右边 */
fixed?: 'left' | 'right'
/** 加到这一列表头和单元格上的类名 */
className?: string
/** 返回单元格要显示的文字 */
formatter?: (row: TableRowData, column: TableColumnConfig, cellValue: unknown) => string
/** 下级列,用来做多级表头。有下级列的列只是表头上的分组,不对应数据 */
children?: TableColumnConfig[]
/** 带边框(border)时能不能拖动表头右边缘调整列宽,默认 true */
resizable?: boolean
/** 拖动时的最小宽度(px),默认 40;auto 没有明确 width 时也约束内容最小宽度 */
minWidth?: number
/** auto 布局的内容最大宽度;明确 width 或拖动宽度优先 */
maxWidth?: number | string
/** 单元格内容只显示一行,放不下时显示省略号,鼠标移上去用提示显示完整内容。不写时跟随表格的 showOverflowTooltip */
showOverflowTooltip?: boolean
}
interface TableSortState {
prop: string
order: TableSortOrder
}
interface TableTreeProps {
/** 子行数组的字段名,默认 `'children'` */
children?: string
/** 叶子标记字段或读取函数,默认 `'isLeaf'`;false 表示待懒加载 */
isLeaf?: string | ((row: TableRowData) => boolean)
}
type TableLoadMethod = (row: TableRowData) => Promise<TableRowData[]>
interface TableLoadErrorContext {
row: TableRowData
key: string | number
error: unknown
}
interface TableSummaryMethodParams {
/** 数据列(不含复选框列、展开列) */
columns: TableColumnConfig[]
/** 第一层的行数据(树形数据的子行不在里面) */
data: TableRowData[]
}
type TableSummaryMethod = (
params: TableSummaryMethodParams
) => (string | number | null | undefined)[]
interface TableSpanMethodParams {
row: TableRowData
column: TableColumnConfig
/** 行号:排序、展开树形节点后看得见的行里的序号,从 0 开始 */
rowIndex: number
/** 数据列的序号,从 0 开始,不含复选框列、展开列 */
columnIndex: number
}
type TableSpanMethod = (
params: TableSpanMethodParams
) => [number, number] | { rowspan: number; colspan: number } | void
另外还导出了 TableEmits、TableContext 和注入用的 TABLE_INJECTION_KEY,自己写和表格配合的子组件时才用得到。
组件 ref 可标注为 TableExpose。仅显式 isLeaf=false 表示待懒加载;true 或未写且无子行按叶子处理。已有非空 children 优先于叶子标记。后端仍用 hasChildren 时可通过 isLeaf: (row) => !row.hasChildren 反向映射。
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>
}