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 或 fillViewport;百分比高度要求父容器有確定高度。無有效約束時保持完整呈現,並在開發環境提示。
- 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>
效能
資料量較大時,請在 setup 裡定義 columns,避免在範本裡以行內方式建立欄位設定。表格會重用內容不變的排序與篩選規格,路徑取值和目前語言的字串比較器也會重用;本機排序先讀取每列的值,再進行比較。
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' | 行的穩定唯一標識;數字回呼保留數字 |
| emptyText | string | 隨語言(中文:暫無資料) | 沒有資料時顯示的文字 |
| selectable | boolean | false | 是否在最左邊顯示核取方塊列 |
| rowSelectable | (row: TableRowData) => boolean | - | 回傳 false 時禁止點擊、全選與 toggleRowSelection;已經選中的禁用行保持原選擇 |
| highlightCurrent | boolean | false | 點擊資料行時設定目前行並高亮,與勾選獨立。 |
| currentKey / v-model:current-key | string | number | null | 內部 null | 屬性存在即受控,包含undefined;null表示清空。 |
| filterValue / v-model:filter-value | TableFilterValue | 內部 {} | 各欄篩選值;屬性存在即受控(含undefined),未傳時由內部保存。 |
| 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 | 清除選中的行 |
| updateLayout | - | 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;遠端查詢需呼叫方自行觸發 |
ref 上還有 selection(按所選 key 順序找到的行,陣列為凍結淺拷貝,行物件身份不變)和深唯讀的 sortState(目前排序)。未知 key 在取到資料之前不會出現在 selection 中。
類型
import type {
TableColumnConfig,
TableSortState,
TableSortOrder,
TableSize,
TableAlign,
TableLayout,
TableProps,
TableTreeProps,
TableLoadMethod,
TableLoadErrorContext,
TableSummaryMethod,
TableSummaryMethodParams,
TableSpanMethod,
TableSpanMethodParams,
TableExpose,
TableScrollToRowOptions,
TableFilterKey,
TableFilterValue,
TableFilterOption,
TableFilterSlotProps,
TableCurrentChangeContext
} 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
setCurrentRow: (row?: TableRowData | null) => void
scrollToRow: (key: string | number, options?: TableScrollToRowOptions) => boolean
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>
}