feat(table): restore useTablePro and add hook demos

Restore the registration tuple and expose readiness, current page rows,
and read-only remote query state.

Add demos for querying, cross-page selection, and export and printing.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-04 15:37:37 +08:00
parent 40320207ac
commit 7de2e4cebf
20 changed files with 866 additions and 58 deletions

View File

@ -1,4 +1,4 @@
import { RTablePro } from '@/components/RTablePro'
import { RTablePro, useTablePro } from '@/components/RTablePro'
import type {
TableProInst,
TableProParams,
@ -13,6 +13,45 @@ const response = (name: string, total = 30): TableProResult => ({
total,
})
it('binds table actions on mount and clears the instance until the table remounts', async () => {
const [
register,
{ isReady, reload, setPage, getTableProInstance, getCurrentPageData },
] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const mountTable = () =>
mount(RTablePro, { props: { columns, request, onRegister: register } })
expect(isReady.value).toBe(false)
expect(getTableProInstance).toThrow('Table is not mounted')
const first = mountTable()
const originalInstance = getTableProInstance()
try {
expect(isReady.value).toBe(true)
await setPage(2)
await flushPromises()
expect(request.mock.lastCall?.[0]).toEqual({ page: 2, pageSize: 10 })
expect(getCurrentPageData()).toEqual(response('Alice').data)
} finally {
first.unmount()
}
expect(isReady.value).toBe(false)
expect(getTableProInstance).toThrow('Table is not mounted')
const second = mountTable()
try {
expect(isReady.value).toBe(true)
expect(getTableProInstance()).not.toBe(originalInstance)
await setPage(2)
await reload(true)
expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 })
} finally {
second.unmount()
}
})
it('loads and paginates once per action, without rewriting the filter object', async () => {
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const filters = { email: '@example.test', page: 99 }
@ -69,7 +108,7 @@ it('ignores stale data even if the loader ignores cancellation', async () => {
const next = instance.setPage(2)
expect(request.mock.calls[0][1].aborted).toBe(true)
second.resolve(response('New page'))
second.resolve(response('New page', 40))
await next
first.resolve(response('Old page'))
await flushPromises()
@ -77,11 +116,84 @@ it('ignores stale data even if the loader ignores cancellation', async () => {
expect(wrapper.text()).toContain('New page')
expect(wrapper.text()).not.toContain('Old page')
expect(wrapper.getComponent(NDataTable).props('loading')).toBe(false)
expect(instance.queryState).toMatchObject({
loading: false,
failed: false,
page: 2,
total: 40,
})
} finally {
wrapper.unmount()
}
})
it('exposes read-only query state during load, failure and retry', async () => {
const initial = Promise.withResolvers<TableProResult>()
const failing = Promise.withResolvers<TableProResult>()
const retry = Promise.withResolvers<TableProResult>()
const request = vi
.fn(() => retry.promise)
.mockReturnValueOnce(initial.promise)
.mockReturnValueOnce(failing.promise)
const [register, { queryState, setPageSize }] = useTablePro()
expect(queryState.value).toBeNull()
const wrapper = mount(RTablePro, {
props: { columns, request, onRegister: register, tool: false },
})
try {
expect(queryState.value).toEqual({
loading: true,
failed: false,
page: 1,
pageSize: 10,
total: null,
})
expect(Reflect.set(queryState.value!, 'page', 99)).toBe(false)
initial.resolve(response('Last successful result', 42))
await flushPromises()
expect(queryState.value).toMatchObject({ loading: false, total: 42 })
const next = setPageSize(20)
expect(queryState.value).toMatchObject({
loading: true,
pageSize: 20,
total: 42,
})
failing.reject(new Error('offline'))
await next
expect(queryState.value).toEqual({
loading: false,
failed: true,
page: 1,
pageSize: 20,
total: 42,
})
expect(wrapper.text()).toContain('Last successful result')
await wrapper.get('.n-alert button').trigger('click')
expect(queryState.value).toMatchObject({
loading: true,
failed: false,
total: 42,
})
retry.resolve(response('Recovered', 7))
await flushPromises()
expect(queryState.value).toMatchObject({
loading: false,
failed: false,
total: 7,
})
} finally {
wrapper.unmount()
}
expect(queryState.value).toBeNull()
})
it('shows a retry for a failed request and omits paging fields when pagination is off', async () => {
const request = vi
.fn(async (_params: TableProParams) => response('Recovered', 1))
@ -100,28 +212,47 @@ it('shows a retry for a failed request and omits paging fields when pagination i
expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}])
expect(wrapper.find('.n-alert').exists()).toBe(false)
expect(wrapper.text()).toContain('Recovered')
expect((wrapper.vm as unknown as TableProInst).queryState).toEqual({
loading: false,
failed: false,
page: null,
pageSize: null,
total: 1,
})
} finally {
wrapper.unmount()
}
})
it('can paginate local data without requiring a request or a row key function', async () => {
it('reads the sorted and filtered local page without a request or custom row key', async () => {
const data = [
{ id: 3, name: 'Third' },
{ id: 1, name: 'First' },
{ id: 2, name: 'Second' },
]
const wrapper = mount(RTablePro, {
props: { columns, data, pageSize: 1, tool: false },
props: {
columns: [{ title: 'Name', key: 'name', sorter: 'default' }],
data,
pageSize: 1,
search: [{ key: 'name', label: 'Name' }],
tool: false,
},
})
try {
expect(wrapper.getComponent(NDataTable).props('remote')).toBe(false)
expect(wrapper.text()).toContain('First')
expect(wrapper.text()).not.toContain('Second')
const instance = wrapper.vm as unknown as TableProInst
expect(instance.getCurrentPageData()).toEqual([data[0]])
instance.getTableInstance()?.sort('name', 'ascend')
await instance.setPage(2)
expect(wrapper.text()).toContain('Second')
expect(instance.getCurrentPageData()).toEqual([data[2]])
await wrapper.get('input').setValue('ir')
await wrapper.get('form').trigger('submit')
expect(instance.getCurrentPageData()).toEqual([data[1]])
} finally {
wrapper.unmount()
}
@ -208,6 +339,7 @@ it('returns to the last available remote page when the total shrinks', async ()
expect(request.mock.calls.map(([params]) => params.page)).toEqual([1, 3, 1])
expect(wrapper.text()).toContain('First page')
expect(instance.queryState).toMatchObject({ page: 1, total: 5 })
} finally {
wrapper.unmount()
}
@ -234,6 +366,7 @@ it('passes native pagination settings and totals through for a manually controll
try {
const pager = wrapper.getComponent(NPagination)
expect((wrapper.vm as unknown as TableProInst).queryState).toBeNull()
expect(pager.props()).toMatchObject({
page: 3,
pageSize: 20,

View File

@ -42,6 +42,9 @@
"TableColumns": "Column preferences",
"TablePrinting": "Printing and custom regions",
"TableCustom": "Slots and instance methods",
"TableHooksQuery": "Hooks · Queries and paging",
"TableHooksSelection": "Hooks · Selection and bulk actions",
"TableHooksOutput": "Hooks · Export and print",
"RouteManagement": "Route management",
"RouteManagementVisual": "Visual editor",
"RouteManagementJson": "JSON configuration"

View File

@ -0,0 +1,38 @@
{
"queryDescription": "Filter by name, change pages, or refresh from outside the table. See the parameters sent by each action.",
"reloadPage": "Refresh current page",
"reloadFirstPage": "Refresh from page 1",
"secondPage": "Go to page 2",
"lastRequest": "Last request",
"requestDetails": "Request {count} · Page {page} · {size} per page · Name: {name}",
"queryStatus": "Remote query status",
"queryPhase": {
"idle": "Waiting for query",
"loading": "Loading",
"failed": "Query failed",
"loaded": "Loaded"
},
"currentPage": "Current page",
"rowsPerPage": "Rows per page",
"resultTotal": "Total results",
"selectionDescription": "Keep selections across pages. Page actions follow the current filter and sort, and bulk marking updates the selected rows.",
"selectPage": "Select current page",
"unselectPage": "Deselect current page",
"clearAll": "Clear all selections",
"markSelected": "Mark selected rows",
"clearSort": "Clear sorting",
"markColumn": "Mark status",
"marked": "Marked",
"unmarked": "Unmarked",
"selectionResult": "Bulk action status",
"selectionDetails": "{selected} selected · {marked} marked",
"outputDescription": "Filter or change pages to compare the two CSV exports. Unmount the table to disable export and print, then mount it again to restore the actions.",
"unmount": "Unmount table",
"mount": "Mount table",
"csvPage": "Export current page as CSV",
"csvLoaded": "Export all loaded rows as CSV",
"mountStatus": "Table instance status",
"ready": "Mounted and ready",
"notReady": "Not mounted",
"printOpened": "Print preview requested"
}

View File

@ -42,6 +42,9 @@
"TableColumns": "列设置与缓存",
"TablePrinting": "打印与自定义区域",
"TableCustom": "插槽与实例操作",
"TableHooksQuery": "Hooks · 查询与分页",
"TableHooksSelection": "Hooks · 选择与批量操作",
"TableHooksOutput": "Hooks · 导出与打印",
"RouteManagement": "路由管理",
"RouteManagementVisual": "可视化配置",
"RouteManagementJson": "JSON 配置"

View File

@ -0,0 +1,38 @@
{
"queryDescription": "从表格外提交姓名筛选、跳页或刷新,查看实际发出的分页和查询条件。",
"reloadPage": "刷新当前页",
"reloadFirstPage": "回首页并刷新",
"secondPage": "跳到第 2 页",
"lastRequest": "最近一次请求",
"requestDetails": "第 {count} 次 · 第 {page} 页 · 每页 {size} 条 · 姓名:{name}",
"queryStatus": "远端查询状态",
"queryPhase": {
"idle": "等待查询",
"loading": "加载中",
"failed": "查询失败",
"loaded": "加载完成"
},
"currentPage": "当前页",
"rowsPerPage": "每页条数",
"resultTotal": "结果总数",
"selectionDescription": "可跨页累计选择。本页操作按表格当前筛选和排序取数,批量标记会更新所选行。",
"selectPage": "选中本页",
"unselectPage": "取消本页选择",
"clearAll": "清空全部选择",
"markSelected": "标记已选行",
"clearSort": "清除排序",
"markColumn": "标记状态",
"marked": "已标记",
"unmarked": "未标记",
"selectionResult": "批量操作状态",
"selectionDetails": "已选 {selected} 条 · 已标记 {marked} 条",
"outputDescription": "筛选或翻页后比较两个 CSV 的范围。卸载表格会禁用导出和打印,重新挂载后恢复。",
"unmount": "卸载表格",
"mount": "挂载表格",
"csvPage": "导出当前页 CSV",
"csvLoaded": "导出全部已加载数据 CSV",
"mountStatus": "表格实例状态",
"ready": "已挂载,可以操作",
"notReady": "未挂载",
"printOpened": "已发起打印预览"
}

View File

@ -115,6 +115,18 @@ const views = {
load: () => import('@/views/demo/tables/custom'),
name: 'TableDemoCustom',
},
'demo/tables/hooks-output': {
load: () => import('@/views/demo/tables/hooks-output'),
name: 'TableDemoHooksOutput',
},
'demo/tables/hooks-query': {
load: () => import('@/views/demo/tables/hooks-query'),
name: 'TableDemoHooksQuery',
},
'demo/tables/hooks-selection': {
load: () => import('@/views/demo/tables/hooks-selection'),
name: 'TableDemoHooksSelection',
},
'demo/tables/printing': {
load: () => import('@/views/demo/tables/printing'),
name: 'TableDemoPrinting',

View File

@ -46,6 +46,24 @@ const tables: AppRouteRecordRaw = {
component: routeView('demo/tables/custom'),
meta: { i18nKey: t('menu.TableCustom') },
},
{
path: 'hooks-query',
name: 'TableDemoHooksQuery',
component: routeView('demo/tables/hooks-query'),
meta: { i18nKey: t('menu.TableHooksQuery') },
},
{
path: 'hooks-selection',
name: 'TableDemoHooksSelection',
component: routeView('demo/tables/hooks-selection'),
meta: { i18nKey: t('menu.TableHooksSelection') },
},
{
path: 'hooks-output',
name: 'TableDemoHooksOutput',
component: routeView('demo/tables/hooks-output'),
meta: { i18nKey: t('menu.TableHooksOutput') },
},
],
}

View File

@ -1,5 +1,4 @@
import { RTablePro } from '@/components'
import type { TableProInst } from '@/components'
import { RTablePro, useTablePro } from '@/components'
import { listPeople } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NFlex, NInput } from 'naive-ui'
@ -10,7 +9,7 @@ export default defineComponent({
setup() {
const { t } = useI18n('table')
const { data } = listPeople()
const table = shallowRef<TableProInst>()
const [register, { setPage, setPageSize }] = useTablePro()
const email = ref('')
const selected = ref<(string | number)[]>([])
const columns = computed(() => [
@ -20,7 +19,7 @@ export default defineComponent({
return () => (
<RTablePro
ref={table}
onRegister={register}
columns={columns.value}
data={data}
v-model:checkedRowKeys={selected.value}
@ -54,18 +53,10 @@ export default defineComponent({
),
title: () => (
<NFlex size={6}>
<NButton
size="small"
secondary
onClick={() => table.value?.setPage(1)}
>
<NButton size="small" secondary onClick={() => setPage(1)}>
{t('firstPage')}
</NButton>
<NButton
size="small"
secondary
onClick={() => table.value?.setPageSize(20)}
>
<NButton size="small" secondary onClick={() => setPageSize(20)}>
{t('twentyRows')}
</NButton>
</NFlex>

View File

@ -0,0 +1,95 @@
import { RTablePro, useTablePro } from '@/components'
import { listPeople } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NFlex } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoHooksOutput',
setup() {
const { t } = useI18n()
const [register, { isReady, downloadCsv, print }] = useTablePro()
const { data } = listPeople()
const mounted = ref(true)
const printResult = ref<boolean>()
const columns = computed(() =>
createPeopleColumns((key) => t(`table.${key}`)).slice(0, 4),
)
return () => (
<DemoPage
title={t('menu.TableHooksOutput')}
description={t('tableHooks.outputDescription')}
>
<NFlex>
<NButton
onClick={() => {
mounted.value = !mounted.value
printResult.value = void 0
}}
>
{t(mounted.value ? 'tableHooks.unmount' : 'tableHooks.mount')}
</NButton>
<NButton
disabled={!isReady.value}
onClick={() => downloadCsv({ fileName: 'people-page' })}
>
{t('tableHooks.csvPage')}
</NButton>
<NButton
disabled={!isReady.value}
onClick={() =>
downloadCsv({ fileName: 'people-loaded', keepOriginalData: true })
}
>
{t('tableHooks.csvLoaded')}
</NButton>
<NButton
disabled={!isReady.value}
onClick={async () => {
printResult.value = await print({
title: t('table.printDemoTitle'),
})
}}
>
{t('table.printDemoTitle')}
</NButton>
</NFlex>
<DemoResult
label={t('tableHooks.mountStatus')}
error={printResult.value === false}
>
{t(isReady.value ? 'tableHooks.ready' : 'tableHooks.notReady')}
{printResult.value === void 0 ? null : (
<div>
{t(
printResult.value
? 'tableHooks.printOpened'
: 'table.printError',
)}
</div>
)}
</DemoResult>
{mounted.value ? (
<RTablePro
onRegister={register}
title={t('table.directory')}
columns={columns.value}
data={data}
search={[
{
key: 'name',
label: t('table.name'),
placeholder: t('table.nameHint'),
},
]}
columnStateKey="demo:hooks-output"
scrollX={562}
/>
) : null}
</DemoPage>
)
},
})

View File

@ -0,0 +1,212 @@
import { getPersonList } from '@/api/demo/mock/person'
import type { PersonListParams } from '@/api/demo/mock/person'
import { RTablePro, useTablePro } from '@/components'
import { useI18n } from '@/hooks/template/useI18n'
import {
NButton,
NCard,
NFlex,
NInput,
NStatistic,
NTag,
NText,
} from 'naive-ui'
import { useId } from 'vue'
import DemoPage from '../components/DemoPage'
import { createPeopleColumns } from './people'
const statusColors = {
idle: 'default',
loading: 'info',
failed: 'error',
loaded: 'success',
} as const
export default defineComponent({
name: 'TableDemoHooksQuery',
setup() {
const { t } = useI18n()
const [register, { isReady, queryState, reload, setPage, setPageSize }] =
useTablePro()
const inputId = useId()
const nameDraft = ref('')
const params = shallowRef<PersonListParams>({})
const lastRequest = shallowRef<PersonListParams>({})
const attempts = ref(0)
const columns = computed(() =>
createPeopleColumns((key) => t(`table.${key}`)).slice(0, 4),
)
const phase = computed(() => {
if (queryState.value?.loading) return 'loading'
if (queryState.value?.failed) return 'failed'
return queryState.value?.total != null ? 'loaded' : 'idle'
})
let failNext = false
const request = async (query: PersonListParams, signal: AbortSignal) => {
const shouldFail = failNext
failNext = false
attempts.value += 1
lastRequest.value = query
// 给演示请求留出可见的加载时间,切页时连同延时一起取消。
await new Promise<void>((resolve, reject) => {
signal.throwIfAborted()
const onAbort = () => {
clearTimeout(timer)
reject(signal.reason)
}
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort)
resolve()
}, 650)
signal.addEventListener('abort', onAbort, { once: true })
})
if (shouldFail) throw new Error(t('table.demoFailure'))
return getPersonList(query, signal)
}
const applyName = (value: string) => {
if (!isReady.value) return
const name = value.trim() || void 0
if (name === params.value.name) {
void reload(true)
} else {
// params 变化已经会回到第一页请求,避免再手动刷新一次。
params.value = { name }
}
}
return () => (
<DemoPage
title={t('menu.TableHooksQuery')}
description={t('tableHooks.queryDescription')}
>
<NCard>
<NFlex vertical>
<form
class="r-table-search"
onSubmit={(event) => {
event.preventDefault()
applyName(nameDraft.value)
}}
>
<div class="r-table-search__field">
<label for={inputId}>{t('table.name')}</label>
<NInput
inputProps={{ id: inputId, name: 'name' }}
v-model:value={nameDraft.value}
placeholder={t('table.nameHint')}
/>
</div>
<div class="r-table-search__actions">
<NButton
attrType="submit"
type="primary"
disabled={!isReady.value}
>
{t('table.search')}
</NButton>
<NButton
disabled={!isReady.value}
onClick={() => {
nameDraft.value = ''
applyName('')
}}
>
{t('table.reset')}
</NButton>
</div>
</form>
<NFlex>
<NButton disabled={!isReady.value} onClick={() => reload()}>
{t('tableHooks.reloadPage')}
</NButton>
<NButton disabled={!isReady.value} onClick={() => reload(true)}>
{t('tableHooks.reloadFirstPage')}
</NButton>
<NButton disabled={!isReady.value} onClick={() => setPage(2)}>
{t('tableHooks.secondPage')}
</NButton>
<NButton
disabled={!isReady.value}
onClick={() => setPageSize(20)}
>
{t('table.twentyRows')}
</NButton>
<NButton
disabled={!isReady.value || queryState.value?.loading}
onClick={() => {
failNext = true
void reload()
}}
>
{t('table.demoFailure')}
</NButton>
</NFlex>
</NFlex>
</NCard>
<NCard title={t('tableHooks.queryStatus')}>
{{
'header-extra': () => (
<NTag
size="small"
type={statusColors[phase.value]}
bordered={false}
>
{t(`tableHooks.queryPhase.${phase.value}`)}
</NTag>
),
default: () => (
<NFlex vertical size={12}>
<NFlex size={[24, 12]}>
<NStatistic
tabularNums
label={t('tableHooks.currentPage')}
value={queryState.value?.page ?? '—'}
/>
<NStatistic
tabularNums
label={t('tableHooks.rowsPerPage')}
value={queryState.value?.pageSize ?? '—'}
/>
<NStatistic
tabularNums
label={t('tableHooks.resultTotal')}
value={queryState.value?.total ?? '—'}
/>
</NFlex>
<NText depth={3}>
{t('tableHooks.lastRequest')}
{' · '}
{t('tableHooks.requestDetails', {
count: attempts.value,
page: lastRequest.value.page ?? '—',
size: lastRequest.value.pageSize ?? '—',
name: lastRequest.value.name ?? '—',
})}
</NText>
</NFlex>
),
}}
</NCard>
<RTablePro
onRegister={register}
title={t('table.directory')}
columns={columns.value}
request={request}
params={params.value}
scrollX={562}
/>
</DemoPage>
)
},
})

View File

@ -0,0 +1,120 @@
import { RTablePro, useTablePro } from '@/components'
import { listPeople } from '@/demo-data/people'
import type { Person } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NFlex } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoHooksSelection',
setup() {
const { t } = useI18n()
const [register, { isReady, getCurrentPageData, getTableInstance }] =
useTablePro()
const { data } = listPeople()
const checked = ref<(string | number)[]>([])
const marked = shallowRef(new Set<string | number>())
const columns = computed<DataTableColumns<Person>>(() => [
{ type: 'selection', width: 44 },
...createPeopleColumns((key) => t(`table.${key}`))
.slice(0, 4)
.map((column) =>
'key' in column && column.key === 'age'
? {
...column,
sorter: (left: Person, right: Person) => left.age - right.age,
}
: column,
),
{
title: t('tableHooks.markColumn'),
key: 'marked',
width: 110,
render: ({ id }) =>
t(marked.value.has(id) ? 'tableHooks.marked' : 'tableHooks.unmarked'),
},
])
const currentKeys = () =>
getCurrentPageData()
.map((row) => row.id)
.filter((id): id is string => typeof id === 'string')
const selectPage = () => {
checked.value = [...new Set([...checked.value, ...currentKeys()])]
}
const unselectPage = () => {
const pageKeys = new Set<string | number>(currentKeys())
checked.value = checked.value.filter((id) => !pageKeys.has(id))
}
const markSelected = () => {
marked.value = new Set([...marked.value, ...checked.value])
checked.value = []
}
return () => (
<DemoPage
title={t('menu.TableHooksSelection')}
description={t('tableHooks.selectionDescription')}
>
<NFlex>
<NButton
type="primary"
disabled={!isReady.value}
onClick={selectPage}
>
{t('tableHooks.selectPage')}
</NButton>
<NButton
disabled={!isReady.value || !checked.value.length}
onClick={unselectPage}
>
{t('tableHooks.unselectPage')}
</NButton>
<NButton
disabled={!checked.value.length}
onClick={() => {
checked.value = []
}}
>
{t('tableHooks.clearAll')}
</NButton>
<NButton disabled={!checked.value.length} onClick={markSelected}>
{t('tableHooks.markSelected')}
</NButton>
<NButton
disabled={!isReady.value}
onClick={() => getTableInstance()?.clearSorter()}
>
{t('tableHooks.clearSort')}
</NButton>
</NFlex>
<DemoResult label={t('tableHooks.selectionResult')}>
{t('tableHooks.selectionDetails', {
selected: checked.value.length,
marked: marked.value.size,
})}
</DemoResult>
<RTablePro
onRegister={register}
title={t('table.directory')}
columns={columns.value}
data={data}
v-model:checkedRowKeys={checked.value}
search={[
{
key: 'name',
label: t('table.name'),
placeholder: t('table.nameHint'),
},
]}
scrollX={716}
/>
</DemoPage>
)
},
})

View File

@ -23,7 +23,6 @@
</p>
<RTablePro
:key="source"
ref="table"
:columns="columns"
:data="source === 'local' ? rows : []"
:request="source === 'remote' ? request : undefined"
@ -33,6 +32,7 @@
]"
columnStateKey="docs-demo"
autoHeight
@register="register"
/>
</div>
</DemoFrame>
@ -40,11 +40,11 @@
<script setup lang="ts">
import { provideUiServices } from '@ray-template/ui/services'
import { RTablePro } from '@ray-template/ui/table-pro'
import type { TableProInst, TableProRequest } from '@ray-template/ui/table-pro'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import type { TableProRequest } from '@ray-template/ui/table-pro'
import { createStorage } from '@ray-template/utils/storage'
import { NButton, NCheckbox, NRadio, NRadioGroup } from 'naive-ui'
import { computed, ref, shallowRef, useId } from 'vue'
import { computed, ref, useId } from 'vue'
import DemoFrame from './DemoFrame.vue'
const props = withDefaults(
@ -82,7 +82,7 @@ const id = useId()
const source = ref<'local' | 'remote'>('local')
const virtual = ref(false)
const cancelled = ref(0)
const table = shallowRef<TableProInst>()
const [register, { reload }] = useTablePro()
const values = new Map<string, string>()
provideUiServices({
@ -150,7 +150,7 @@ const request: TableProRequest = (
}
const failRequest = () => {
failNext = true
void table.value?.reload()
void reload()
}
</script>

View File

@ -9,13 +9,13 @@
## v6 的变更
| 领域 | v6 的入口与约定 |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 应用结构 | 原来根目录的 `src/`、`mock/`、`public/`、应用环境文件和 `index.html` 归入 `apps/admin/`。环境变量、容器配置和构建脚本应按 v6 入口重新核对。 |
| 组件与工具 | 从各包的公开入口导入共享能力,例如 `@ray-template/ui/table-pro`、`@ray-template/composables/useDevice` 和 `@ray-template/utils/precision`。Ray Admin 内部的 `@/` 指向自己的 `src/`。 |
| 组件接入 | v6 的 TablePro 统一使用 `RTablePro`,可传 `data` 或 `request(params, signal)`。按现行 API 接入搜索、分页、列设置、CSV 和打印。 |
| 路由、权限与请求 | 路由校验、请求客户端和布局由共享包提供。Ray Admin 在应用侧提供页面注册表、会话和鉴权、请求头、主题和语言。 |
| 文档与演示 | VitePress 位于 `apps/docs/`,通过公共包运行示例。官方发布中后台位于 `/ray-template/`,v6 文档位于 `/ray-template/docs/`。 |
| 领域 | v6 的入口与约定 |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 应用结构 | 原来根目录的 `src/`、`mock/`、`public/`、应用环境文件和 `index.html` 归入 `apps/admin/`。环境变量、容器配置和构建脚本应按 v6 入口重新核对。 |
| 组件与工具 | 从各包的公开入口导入共享能力,例如 `@ray-template/ui/table-pro`、`@ray-template/composables/useDevice` 和 `@ray-template/utils/precision`。Ray Admin 内部的 `@/` 指向自己的 `src/`。 |
| 组件接入 | v6 的 TablePro 统一使用 `RTablePro`,可传 `data` 或 `request(params, signal)`。`useTablePro` 保留 `[register, actions]` 和 `onRegister`,请求与实例方法使用[现行 API](./reference/table-pro#usetablepro)。 |
| 路由、权限与请求 | 路由校验、请求客户端和布局由共享包提供。Ray Admin 在应用侧提供页面注册表、会话和鉴权、请求头、主题和语言。 |
| 文档与演示 | VitePress 位于 `apps/docs/`,通过公共包运行示例。官方发布中后台位于 `/ray-template/`,v6 文档位于 `/ray-template/docs/`。 |
## 现有项目采用 v6

View File

@ -68,7 +68,52 @@ const renderTable = () => (
)
```
实例还提供 `setPage`、`setPageSize`、`downloadCsv`、`print` 和 `getTableInstance`。扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。
实例还提供 `setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print` 和 `getTableInstance`。扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。
### `useTablePro`
也可以用同一入口导出的 `useTablePro` 注册实例,保留 `[register, actions]` 的写法:
```tsx
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
const [register, { isReady, reload }] = useTablePro()
const renderTable = () => (
<>
<button disabled={!isReady.value} onClick={() => reload(true)}>
回首页并刷新
</button>
<RTablePro
onRegister={register}
columns={[{ title: '姓名', key: 'name' }]}
/>
</>
)
```
SFC 使用 `<RTablePro @register="register" />`。每张表单独调用一次 Hook;表格挂载后注册,卸载时清除。`actions` 提供上述实例方法、`getTableProInstance()` 和只读 `isReady`;它表示实例已绑定,和请求是否完成无关。未绑定时调用实例方法会抛错。
从 `actions` 解构 `queryState`,用 `queryState.value` 响应式读取 TablePro 管理的远端请求。通过组件 ref 使用时,读取 `table.value?.queryState`。
| 字段 | 含义 |
| ------------------- | ------------------------------------------------------------------------------- |
| `loading` | 当前请求是否正在执行。只反映 `request`,与外部 `loading` prop 无关。 |
| `failed` | 当前请求是否失败。重试开始时清除;错误详情可通过 `onRequestError` 接收。 |
| `page` / `pageSize` | 当前页码和每页条数;关闭分页时两者为 `null`。 |
| `total` | 最近一次成功结果的筛选后总数。首次成功前为 `null`,刷新和失败期间保留上次的值。 |
`queryState` 的值和字段均为只读。未挂载、已卸载、未传 `request`(包括手动远端模式)时,值为 `null`。被取消的旧请求不会覆盖当前查询状态。
`getCurrentPageData()` 返回当前页的行:本地表格已应用筛选、排序和分页,远端表格返回当前已加载的数据。返回的行用于读取,业务变更通过页面数据完成;虚拟滚动不会缩小取数范围。旧版 `runTableRequest` / `runAsyncTableRequest` 迁移到 `reload`,请求条件通过 `params` 或请求函数传入。
Ray Admin 的「表格」菜单下有三个可运行的完整示例:
| 示例 | 可以试什么 |
| --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| [Hooks · 查询与分页](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/demo/tables/hooks-query.tsx) | 通过 `params` 查询,观察加载、失败和分页数据。可模拟失败、重试,并查看实际发出的请求。 |
| [Hooks · 选择与批量操作](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/demo/tables/hooks-selection.tsx) | 按当前页选择或取消,跨页保留选择,对所选行应用批量标记;通过底层实例清除排序。 |
| [Hooks · 导出与打印](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/demo/tables/hooks-output.tsx) | 对比当前页与全部已加载数据的 CSV,打印当前页,观察卸载和重新挂载时按钮的可用状态。 |
## 列设置与缓存
@ -80,7 +125,7 @@ const renderTable = () => (
CSV 的 `keepOriginalData` 使用当前传给表格的整批数据,远端模式不会自动抓取全部页。列级 `allowExport: false` 可排除数据;`getCsvCell` / `getCsvHeader` 返回原始文本,由组件做 CSV 转义。
[TablePro 完整契约](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/README.md) · [六种可运行示例](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main/apps/admin/src/views/demo/tables) · [v6 的变更](../migration#v6-的变更)
[TablePro 完整契约](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/README.md) · [全部表格示例](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main/apps/admin/src/views/demo/tables) · [v6 的变更](../migration#v6-的变更)
## Props、事件和插槽

View File

@ -4,14 +4,14 @@
官网当前面向 v6,源码链接使用 Monorepo 路径,发布构建时用 `RAY_TEMPLATE_SOURCE_REF` 固定到发布提交。页内示例随工作区源码构建。v5 的源码与发布标签见[版本分界](../apps/docs/migration.md)。
| 领域 | 应用侧证据 | 必须交代的边界 |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 组件入口与 TablePro | [公开导出](../apps/admin/src/components/index.ts)、[TablePro 契约](../apps/admin/src/components/RTablePro/README.md)、[六个示例](../apps/admin/src/views/demo/tables) | `base/`、`pro/` 深层路径失效;`RTable`、`useTable`、`useTablePro` 已移除。远端 `total` 是筛选后的总数;取消依赖请求函数传递 signal;导出和打印默认仅当前页可见数据列。 |
| 路由与权限 | [路由说明](../apps/admin/src/router/README.md)、[路由类型](../apps/admin/src/router/types.ts)、[权限守卫](../apps/admin/src/router/utils/permission.ts) | 菜单显隐不等于访问授权;会话和接口权限由后端校验。缓存需要路由 name 对应组件 name,验证菜单进入、直达和刷新。 |
| 布局与 Pinia | [布局插槽和偏好](../apps/admin/src/layout/README.md)、[Store 约定](../apps/admin/src/store/README.md) | 全局 UI 单例已迁入 `runtime`,不持久化。保留历史设置和锁屏格式;自定义内容插槽时,由接入方负责保留请求取消及路由缓存。 |
| 请求与 Mock | [Axios 实现](../apps/admin/src/axios/instance.ts)、[取消器](../apps/admin/src/axios/utils/RequestCanceler.ts)、[人员查询](../apps/admin/src/api/demo/mock/person.ts) | 实例成功返回 body,失败拒绝;调用方传 signal 时关闭模板的默认 signal 注入。Mock HTTP 仅用于开发,静态演示有独立本地数据分支。 |
| Hooks、工具与图标 | [Hooks 行为](../apps/admin/src/hooks/README.md)、[工具兼容入口](../apps/admin/src/utils/README.md)、[图标生成](../packages/icons/src/A_README.md) | `@/hooks` 与 `@/utils` 公共入口保留;旧裸图标仅在缓存读取边界按唯一名称迁移。截图和打印测试不代表原生浏览器能力验收。 |
| 工具链与部署 | [工具链记录](toolchain-upgrade.md)、[架构地图](architecture.md)、[Vite 配置](../vite.custom.config.ts) | Node/pnpm 以清单为准。应用 base 为 `/ray-template/`,内置文档为 `/ray-template/docs/`。已发布旧站仍使用 `/ray-template-doc/`。 |
| 领域 | 应用侧证据 | 必须交代的边界 |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 组件入口与 TablePro | [公开导出](../apps/admin/src/components/index.ts)、[TablePro 契约](../apps/admin/src/components/RTablePro/README.md)、[表格示例](../apps/admin/src/views/demo/tables) | `base/`、`pro/` 深层路径失效;`RTable`、`useTable` 已移除。`useTablePro` 保留注册写法,提供 `isReady` 和当前页取数。远端 `total` 是筛选后的总数;取消依赖请求函数传递 signal;导出和打印默认仅当前页可见数据列。 |
| 路由与权限 | [路由说明](../apps/admin/src/router/README.md)、[路由类型](../apps/admin/src/router/types.ts)、[权限守卫](../apps/admin/src/router/utils/permission.ts) | 菜单显隐不等于访问授权;会话和接口权限由后端校验。缓存需要路由 name 对应组件 name,验证菜单进入、直达和刷新。 |
| 布局与 Pinia | [布局插槽和偏好](../apps/admin/src/layout/README.md)、[Store 约定](../apps/admin/src/store/README.md) | 全局 UI 单例已迁入 `runtime`,不持久化。保留历史设置和锁屏格式;自定义内容插槽时,由接入方负责保留请求取消及路由缓存。 |
| 请求与 Mock | [Axios 实现](../apps/admin/src/axios/instance.ts)、[取消器](../apps/admin/src/axios/utils/RequestCanceler.ts)、[人员查询](../apps/admin/src/api/demo/mock/person.ts) | 实例成功返回 body,失败拒绝;调用方传 signal 时关闭模板的默认 signal 注入。Mock HTTP 仅用于开发,静态演示有独立本地数据分支。 |
| Hooks、工具与图标 | [Hooks 行为](../apps/admin/src/hooks/README.md)、[工具兼容入口](../apps/admin/src/utils/README.md)、[图标生成](../packages/icons/src/A_README.md) | `@/hooks` 与 `@/utils` 公共入口保留;旧裸图标仅在缓存读取边界按唯一名称迁移。截图和打印测试不代表原生浏览器能力验收。 |
| 工具链与部署 | [工具链记录](toolchain-upgrade.md)、[架构地图](architecture.md)、[Vite 配置](../vite.custom.config.ts) | Node/pnpm 以清单为准。应用 base 为 `/ray-template/`,内置文档为 `/ray-template/docs/`。已发布旧站仍使用 `/ray-template-doc/`。 |
## 联动流程

View File

@ -26,9 +26,26 @@ import { RTablePro } from '@/components'
- 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。
- `autoHeight` 默认使用当前布局的可用高度,宿主外部使用视口高度;嵌入特定区域时可以用 CSS 变量 `--r-table-height` 覆盖。较短的屏幕保留表格的最小操作高度。
- 只接收最新的请求结果。失败时保留已加载的数据并显示重试;可以用 `onRequestError` 处理错误,或用 `error` 插槽定制提示。
- 需要实例时使用 `shallowRef<TableProInst>()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`downloadCsv`、`print` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。
- 需要实例时使用 `shallowRef<TableProInst>()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。
迁移时,把旧 `RTable` 改为 `RTablePro bare`(需要完整工具栏时省略 `bare`),把 `useTable` / `useTablePro` 的注册改为可选的实例 ref。旧版 `requestConfig` 可改为 `params` 或请求函数内的字段映射;`takeoverAutoHeight`、`flexAutoHeight` 改为 `autoHeight`。
## 注册 Hook
也可以从 `@ray-template/ui/table-pro` 或 Ray Admin 的 `@/components` 导入 `useTablePro`。每张表调用一次,保持 `[register, actions]` 和 `onRegister` 的用法:
```tsx
const [register, { reload }] = useTablePro()
const renderTable = () => <RTablePro onRegister={register} columns={columns} />
const reloadFromFirstPage = () => reload(true)
```
在 SFC 中使用 `@register="register"`。注册发生在表格挂载后,卸载时清除绑定。`actions` 可解构,包含 `TableProInst` 的方法、`getTableProInstance()` 和只读 `isReady`。表格外的按钮可用 `disabled={!isReady.value}`;`isReady` 只表示实例已绑定,未绑定时调用实例方法会抛错。
`actions.queryState.value` 是组件管理的远端查询状态,实例 ref 则用 `table.value?.queryState`。未挂载或未传 `request` 时为 `null`。只读快照包含 `loading`、`failed`、`page`、`pageSize` 和 `total`;关闭分页时页码和每页条数为 `null`。`total` 在首次成功前为 `null`,刷新和失败时保留上次成功结果。外部 `loading` 不计入查询状态,错误详情由 `onRequestError` 报告。
`getCurrentPageData()` 适合本页批量操作。本地模式读取排序、筛选、分页后的行;远端模式读取当前已加载的数据,不会请求其他页。它返回对行的只读引用,不受虚拟滚动窗口影响;选择和批量变更仍由页面通过 `v-model:checkedRowKeys` 和业务数据管理。
迁移时,把旧 `RTable` 改为 `RTablePro bare`(需要完整工具栏时省略 `bare`),用 `useTablePro` 或实例 ref 替代 `useTable`。旧版 `runTableRequest` / `runAsyncTableRequest` 改用 `reload`,需要回第一页时调用 `reload(true)`。`requestConfig` 改用 `params` 或在请求函数内映射字段;`takeoverAutoHeight`、`flexAutoHeight` 改为 `autoHeight`。
## 列显示与缓存
@ -63,4 +80,4 @@ CSV 默认导出当前页可见数据列;`keepOriginalData` 使用传入的整
普通列配置、选择、展开、排序、筛选、汇总、虚拟滚动、固定列、空状态和加载插槽沿用 [DataTable API](https://www.naiveui.com/zh-CN/components/data-table)。`pagination` 对象透传 [Pagination API](https://www.naiveui.com/zh-CN/components/pagination) 的配置,包括快速跳页、页码模板和回调。配置了 `request` 时页码、每页条数和总数由 TablePro 管理;初始页用 `pagination.defaultPage`,运行时跳页用实例 `setPage`。手动远端模式可以直接传 `remote + data + pagination`。服务端排序、过滤继续使用 Naive UI 的事件,在调用方将条件传给 `params`,组件不会推断接口字段。页数很大时可配置 `pagination.showQuickJumpDropdown: false`。
在「表格」菜单下,可分别查看纯表格、远端查询与分页(含服务端排序和错误重试)、自适应高度(含虚拟滚动)、列设置与缓存、默认和自定义打印、插槽与实例操作。旧示例路径会重定向到对应子页。
在「表格」菜单下,除了纯表格、远端查询、自适应高度、列设置、打印和插槽示例,还可以查看三个独立的 Hooks 示例:查询与分页、选择与批量操作、导出与打印。旧示例路径会重定向到对应子页。

View File

@ -1,7 +1,9 @@
export { default as RTablePro } from './src/TablePro'
export { useTablePro } from './src/useTablePro'
export type { TableProInst, TableProProps } from './src/TablePro'
export type {
TableProParams,
TableProQueryState,
TableProRequest,
TableProResult,
TableProSearchField,

View File

@ -5,6 +5,7 @@ import {
computed,
defineComponent,
onBeforeUnmount,
onMounted,
ref,
shallowRef,
watch,
@ -17,6 +18,7 @@ import TablePanel from './TablePanel'
import type {
TablePanelInst,
TableProParams,
TableProQueryState,
TableProRequest,
TableProResult,
TableProSearchField,
@ -26,6 +28,8 @@ import type {
const positiveInteger = (value: number) =>
Number.isSafeInteger(value) && value > 0
const emptyRemoteRows: TableProResult['data'] = []
const props = {
...tableProps,
pagination: {
@ -34,6 +38,7 @@ const props = {
},
pageSize: { type: Number, default: 10 },
request: Function as PropType<TableProRequest>,
onRegister: Function as PropType<(instance: TableProInst) => void>,
params: Object,
search: Array as PropType<TableProSearchField[]>,
rowKey: {
@ -46,9 +51,11 @@ const props = {
export type TableProProps = ExtractPublicPropTypes<typeof props>
export interface TableProInst extends TablePanelInst {
readonly queryState: TableProQueryState | null
reload: (resetPage?: boolean) => Promise<void>
setPage: (page: number) => Promise<void>
setPageSize: (pageSize: number) => Promise<void>
getCurrentPageData: () => readonly Readonly<Record<string, unknown>>[]
}
export default defineComponent({
@ -59,9 +66,8 @@ export default defineComponent({
setup(props, { attrs, slots, expose, emit }) {
const { t } = useTableLocale()
const table = shallowRef<TablePanelInst>()
const result = shallowRef<TableProResult>({ data: [], total: 0 })
const loading = ref(false)
const failed = ref(false)
const result = shallowRef<TableProResult>()
const requestPhase = ref<'idle' | 'loading' | 'failed'>('idle')
const searchValues = shallowRef<TableSearchValues>({})
const pagination = computed(() => props.pagination ?? !props.bare)
const pagerOptions = computed(() =>
@ -78,6 +84,19 @@ export default defineComponent({
const firstPage = pagerOptions.value?.defaultPage ?? 1
const page = ref(positiveInteger(firstPage) ? firstPage : 1)
const pageSize = ref(configuredPageSize.value)
const queryState = computed<TableProQueryState | null>(() => {
if (!props.request) return null
const paginated = pagination.value !== false
return Object.freeze({
loading: requestPhase.value === 'loading',
failed: requestPhase.value === 'failed',
page: paginated ? page.value : null,
pageSize: paginated ? pageSize.value : null,
total: result.value?.total ?? null,
})
})
const localRows = computed(() => {
const entries = Object.entries(searchValues.value)
@ -105,12 +124,11 @@ export default defineComponent({
if (resetPage) page.value = 1
pending?.abort()
failed.value = false
const { request, params } = props
if (!request) {
pending = void 0
loading.value = false
requestPhase.value = 'idle'
return
}
@ -118,7 +136,7 @@ export default defineComponent({
const current = new AbortController()
pending = current
loading.value = true
requestPhase.value = 'loading'
// 分页字段由表格统一管理,筛选参数不能覆盖当前页码。
const query: TableProParams = { ...params, ...searchValues.value }
@ -163,12 +181,13 @@ export default defineComponent({
} catch (error) {
if (current.signal.aborted) return
failed.value = true
requestPhase.value = 'failed'
emit('request-error', error)
} finally {
if (pending === current) {
pending = void 0
loading.value = false
if (requestPhase.value === 'loading') requestPhase.value = 'idle'
}
}
}
@ -218,19 +237,26 @@ export default defineComponent({
})
const instance: TableProInst = {
get queryState() {
return queryState.value
},
reload,
setPage,
setPageSize,
getTableInstance: () => table.value?.getTableInstance() ?? null,
getCurrentPageData: () =>
table.value?.getTableInstance()?.getCurrentPageData() ?? [],
print: (options) => table.value?.print(options) ?? Promise.resolve(false),
downloadCsv: (options) => table.value?.downloadCsv(options),
}
expose(instance)
onMounted(() => props.onRegister?.(instance))
return () => {
const {
request,
onRegister: _onRegister,
params,
pagination: _pagination,
pageSize: _pageSize,
@ -256,7 +282,7 @@ export default defineComponent({
? pageSize.value
: (options?.pageSize ?? pageSize.value),
...(request
? { itemCount: result.value.total, pageCount: void 0 }
? { itemCount: result.value?.total ?? 0, pageCount: void 0 }
: {}),
}
@ -266,8 +292,10 @@ export default defineComponent({
{...rest}
ref={table}
remote={!!request || remote}
data={request ? result.value.data : localRows.value}
loading={loading.value || externalLoading}
data={
request ? (result.value?.data ?? emptyRemoteRows) : localRows.value
}
loading={requestPhase.value === 'loading' || externalLoading}
pagination={paginationProps}
onUpdatePage={(value) => {
void setPage(value)
@ -288,7 +316,7 @@ export default defineComponent({
? () => <Search fields={search} onSearch={submitSearch} />
: void 0,
notice: () =>
failed.value
requestPhase.value === 'failed'
? (error?.({ reload }) ?? (
<NAlert type="error" title={t('requestError')}>
<NButton size="small" secondary onClick={() => reload()}>

View File

@ -30,6 +30,14 @@ export interface TableProResult {
total: number
}
export interface TableProQueryState {
readonly loading: boolean
readonly failed: boolean
readonly page: number | null
readonly pageSize: number | null
readonly total: number | null
}
export type TableProRequest = (
params: TableProParams,
signal: AbortSignal,

View File

@ -0,0 +1,45 @@
import { computed, onScopeDispose, shallowRef } from 'vue'
import type { ComputedRef } from 'vue'
import type { TableProInst } from './TablePro'
export const useTablePro = () => {
const table = shallowRef<TableProInst>()
const register = (instance: TableProInst) => {
table.value = instance
// onRegister 在表格的挂载作用域内调用,卸载时只清理对应的实例。
onScopeDispose(() => {
if (table.value === instance) table.value = void 0
}, true)
}
const getTableProInstance = () => {
if (!table.value) {
throw new Error(
'[useTablePro] Table is not mounted. Bind register to onRegister.',
)
}
return table.value
}
const actions: Omit<TableProInst, 'queryState'> & {
isReady: ComputedRef<boolean>
queryState: ComputedRef<TableProInst['queryState']>
getTableProInstance: () => TableProInst
} = {
isReady: computed(() => table.value !== void 0),
queryState: computed(() => table.value?.queryState ?? null),
getTableProInstance,
reload: (resetPage) => getTableProInstance().reload(resetPage),
setPage: (page) => getTableProInstance().setPage(page),
setPageSize: (pageSize) => getTableProInstance().setPageSize(pageSize),
getCurrentPageData: () => getTableProInstance().getCurrentPageData(),
getTableInstance: () => getTableProInstance().getTableInstance(),
print: (options) => getTableProInstance().print(options),
downloadCsv: (options) => getTableProInstance().downloadCsv(options),
}
return [register, actions] as const
}