feat(table)!: consolidate TablePro and refresh table demos

Group table demos and share their dataset across the development Mock API
and static previews. Restore focus after maximizing content and add column
preferences, printing, and CSV export to TablePro.

BREAKING CHANGE: RTable and the legacy registration hooks are removed.
Use RTablePro props, slots, or the exposed instance instead.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-03 16:04:49 +08:00
parent e84908b668
commit 8079e2d4f5
83 changed files with 3282 additions and 4275 deletions

View File

@ -0,0 +1,211 @@
import { RTablePro } from '@/components/base/RTablePro'
import { useColumnVisibility } from '@/components/base/RTablePro/src/columns'
import ColumnSettings from '@/components/base/RTablePro/src/components/C'
import { prefixCacheKey } from '@/utils/app/prefix-cache-key'
import { mount } from '@vue/test-utils'
import { NDataTable, NTree } from 'naive-ui'
import type { DataTableColumn } from 'naive-ui'
import { effectScope, nextTick, ref, shallowRef } from 'vue'
const name = { key: 'name', title: 'Name' }
const email = { key: 'email', title: 'Email' }
const region = { key: 'region', title: 'Region' }
const group = { key: 'contact', title: 'Contact', children: [name, email] }
const selection = { type: 'selection' as const }
const columns = shallowRef<DataTableColumn[]>([selection, group, region])
const cacheKey = (key: string) => prefixCacheKey(`table-pro:columns:v1:${key}`)
afterEach(() => {
localStorage.clear()
columns.value = [selection, group, region]
})
it('stores only hidden leaf keys, restores them on mount, and isolates separate keys', () => {
const scope = effectScope()
const second = effectScope()
const key = ref('directory')
try {
const first = scope.run(() => useColumnVisibility(columns, key))!
expect(first.visibleColumns.value).toBe(columns.value)
expect(localStorage.length).toBe(0)
first.setColumnVisible('email', false)
expect(first.visibleColumns.value).toEqual([
selection,
{ ...group, children: [name] },
region,
])
expect(JSON.parse(localStorage.getItem(cacheKey('directory'))!)).toEqual([
'email',
])
const restored = second.run(() => useColumnVisibility(columns, key))!
const other = second.run(() => useColumnVisibility(columns, ref('other')))!
expect(restored.visibleColumns.value).toEqual(first.visibleColumns.value)
expect(other.visibleColumns.value).toBe(columns.value)
restored.resetColumns()
expect(localStorage.getItem(cacheKey('directory'))).toBeNull()
} finally {
scope.stop()
second.stop()
}
})
it('ignores stale keys, shows new columns, and keeps one data column visible', async () => {
localStorage.setItem(
cacheKey('directory'),
JSON.stringify(['name', 'region', 'removed', false]),
)
const scope = effectScope()
try {
const state = scope.run(() =>
useColumnVisibility(columns, ref('directory')),
)!
expect(state.hiddenKeys.value).toEqual(new Set(['name', 'region']))
state.setColumnVisible('email', false)
expect(state.visibleColumns.value).toEqual([
selection,
{ ...group, children: [email] },
])
columns.value = [selection, name, { key: 'created', title: 'Created' }]
await nextTick()
expect(state.visibleColumns.value).toEqual([
selection,
{ key: 'created', title: 'Created' },
])
columns.value = [selection, name]
expect(state.visibleColumns.value).toEqual([selection, name])
} finally {
scope.stop()
}
})
it('updates visibility without touching storage when no key is configured', () => {
const scope = effectScope()
try {
const state = scope.run(() => useColumnVisibility(columns, ref()))!
state.setColumnVisible('email', false)
expect(state.hiddenKeys.value.has('email')).toBe(true)
expect(localStorage.length).toBe(0)
} finally {
scope.stop()
}
})
it('provides the full settings with a frozen plain columns array and keeps adjustments when definitions change', async () => {
const input: DataTableColumn[] = [
selection,
{ ...name, width: 120 },
{ ...email, width: 180 },
]
input.forEach(Object.freeze)
Object.freeze(input)
const wrapper = mount(RTablePro, {
props: {
columns: input,
data: [{ id: 1, name: 'Alice', email: 'alice@example.test' }],
},
})
try {
const settings = wrapper.getComponent(ColumnSettings)
const table = wrapper.getComponent(NDataTable)
await settings.get('button').trigger('click')
const tree = wrapper.getComponent(NTree)
const drop = tree.props('onDrop')
expect(tree.props('draggable')).toBe(true)
if (typeof drop !== 'function')
throw new Error('Missing column drop handler')
drop({
node: { key: 'name' },
dragNode: { key: 'email' },
dropPosition: 'before',
event: new DragEvent('drop'),
})
settings.vm.$emit('patchColumn', 'email', {
fixed: 'left',
resizable: true,
})
await nextTick()
expect(table.props('columns')).toEqual([
selection,
{ ...input[2], fixed: 'left', resizable: true },
input[1],
])
expect(input).toEqual([
selection,
{ ...name, width: 120 },
{ ...email, width: 180 },
])
settings.vm.$emit('toggleColumn', 'name', false)
await wrapper.setProps({
columns: [
selection,
{ ...name, width: 130 },
region,
{ ...email, title: 'Work email', width: 220 },
],
})
expect(table.props('columns')).toEqual([
selection,
{
...email,
title: 'Work email',
width: 220,
fixed: 'left',
resizable: true,
},
region,
])
settings.vm.$emit('toggleColumn', 'name', true)
await nextTick()
expect(table.props('columns')?.at(-1)).toEqual({ ...name, width: 130 })
} finally {
wrapper.unmount()
}
})
it('lets v-model own the full column definitions without removing hidden columns from the emitted value', async () => {
const input = [selection, name, email]
const update = vi.fn()
const wrapper = mount(RTablePro, {
props: { columns: input, 'onUpdate:columns': update },
})
try {
const settings = wrapper.getComponent(ColumnSettings)
const table = wrapper.getComponent(NDataTable)
settings.vm.$emit('toggleColumn', 'email', false)
settings.vm.$emit('reorderColumns', ['email', 'name'])
await nextTick()
expect(update).toHaveBeenCalledExactlyOnceWith([selection, email, name])
expect(table.props('columns')).toEqual([selection, name])
await wrapper.setProps({ columns: update.mock.calls[0][0] })
settings.vm.$emit('toggleColumn', 'email', true)
await nextTick()
expect(table.props('columns')).toEqual([selection, email, name])
expect(update).toHaveBeenCalledTimes(1)
} finally {
wrapper.unmount()
}
})

View File

@ -0,0 +1,99 @@
import { RTablePro } from '@/components/base/RTablePro'
import type { TableProInst } from '@/components/base/RTablePro'
import { buildTableCsv } from '@/components/base/RTablePro/src/csv'
import * as printing from '@/components/base/RTablePro/src/printing'
import { mount } from '@vue/test-utils'
import type { DataTableColumn } from 'naive-ui'
afterEach(() => vi.restoreAllMocks())
it('prints every row from the active page, even with virtual rows, without UI chrome', async () => {
const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true)
const wrapper = mount(RTablePro, {
props: {
data: Array.from({ length: 24 }, (_, id) => ({
id,
name: `Person ${id}`,
})),
columns: [{ type: 'selection' }, { key: 'name', title: 'Name' }],
search: [{ key: 'name', label: 'Search name' }],
autoHeight: true,
virtualScroll: true,
pageSize: 12,
},
slots: { tableFooter: 'Only on screen' },
})
try {
const instance = wrapper.vm as unknown as TableProInst
await instance.setPage(2)
expect(await instance.print()).toBe(true)
const content = print.mock.calls[0][0]
expect(content.tagName).toBe('TABLE')
expect(content.querySelectorAll('th')).toHaveLength(1)
expect(content.querySelectorAll('tbody tr')).toHaveLength(12)
expect(content.querySelector('tbody tr')?.textContent).toBe('Person 12')
expect(content.textContent).not.toMatch(
/Search name|Only on screen|Person 11/,
)
} finally {
wrapper.unmount()
}
})
it('prints only the chosen region and leaves the source untouched', async () => {
const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true)
const target = document.createElement('section')
target.innerHTML =
'<h2>Summary</h2><button onclick="alert(1)">Screen action</button>'
const wrapper = mount(RTablePro, {
props: { data: [{ id: 1 }], columns: [{ key: 'id', title: 'ID' }] },
})
try {
const instance = wrapper.vm as unknown as TableProInst
expect(
await instance.print({ target: () => target, title: 'Report' }),
).toBe(true)
expect(await instance.print({ target: () => null })).toBe(false)
expect(print).toHaveBeenCalledTimes(1)
const [content, options] = print.mock.calls[0]
expect(content.querySelector('h2')?.textContent).toBe('Summary')
expect(content.querySelector('button')?.hasAttribute('onclick')).toBe(false)
expect(content.querySelector('table')).toBeNull()
expect(target.querySelector('button')?.hasAttribute('onclick')).toBe(true)
expect(options.title).toBe('Report')
} finally {
wrapper.unmount()
}
})
it('exports group children with correct CSV escaping and neutralizes formula text', () => {
const columns: DataTableColumn[] = [
{ type: 'selection' },
{
key: 'group',
children: [
{ key: 'name', title: 'Name' },
{ key: 'note', title: 'Note' },
{ key: 'private', title: 'Private', allowExport: false },
],
},
{ key: 'score', title: 'Score' },
]
expect(
buildTableCsv(columns, [
{ name: 'A, "B"', note: '=2+2', score: -2 },
{ name: 'Array value', note: ['=2+2', 'text'], score: -2n },
]),
).toBe(
'"Name","Note","Score"\r\n"A, ""B""","\'=2+2","-2"\r\n"Array value","\'=2+2,text","-2"',
)
})

View File

@ -0,0 +1,320 @@
import { RTablePro } from '@/components/base/RTablePro'
import type {
TableProInst,
TableProParams,
TableProResult,
} from '@/components/base/RTablePro'
import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NPagination } from 'naive-ui'
const columns = [{ title: 'Name', key: 'name' }]
const response = (name: string, total = 30): TableProResult => ({
data: [{ id: name, name }],
total,
})
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 }
const wrapper = mount(RTablePro, {
props: { columns, request, params: filters, tool: false },
})
try {
await flushPromises()
expect(request.mock.calls).toEqual([
[
{ email: '@example.test', page: 1, pageSize: 10 },
expect.any(AbortSignal),
],
])
const table = wrapper.getComponent(NDataTable)
expect(table.props('remote')).toBe(true)
expect(table.props('data')).toEqual(response('Alice').data)
expect(wrapper.getComponent(NPagination).props('itemCount')).toBe(30)
const instance = wrapper.vm as unknown as TableProInst
await instance.setPage(2)
await instance.setPageSize(20)
await instance.setPage(2)
await wrapper.setProps({ params: { email: 'alice' } })
await flushPromises()
expect(request.mock.calls.map(([params]) => params)).toEqual([
{ email: '@example.test', page: 1, pageSize: 10 },
{ email: '@example.test', page: 2, pageSize: 10 },
{ email: '@example.test', page: 1, pageSize: 20 },
{ email: '@example.test', page: 2, pageSize: 20 },
{ email: 'alice', page: 1, pageSize: 20 },
])
expect(filters).toEqual({ email: '@example.test', page: 99 })
} finally {
wrapper.unmount()
}
})
it('ignores stale data even if the loader ignores cancellation', async () => {
const first = Promise.withResolvers<TableProResult>()
const second = Promise.withResolvers<TableProResult>()
const request = vi
.fn((_params: TableProParams, _signal: AbortSignal) => first.promise)
.mockImplementationOnce(() => first.promise)
.mockImplementationOnce(() => second.promise)
const wrapper = mount(RTablePro, { props: { columns, request, tool: false } })
try {
const instance = wrapper.vm as unknown as TableProInst
const next = instance.setPage(2)
expect(request.mock.calls[0][1].aborted).toBe(true)
second.resolve(response('New page'))
await next
first.resolve(response('Old page'))
await flushPromises()
expect(wrapper.text()).toContain('New page')
expect(wrapper.text()).not.toContain('Old page')
expect(wrapper.getComponent(NDataTable).props('loading')).toBe(false)
} finally {
wrapper.unmount()
}
})
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))
.mockRejectedValueOnce(new Error('offline'))
const wrapper = mount(RTablePro, {
props: { columns, request, pagination: false, tool: false },
})
try {
await flushPromises()
expect(wrapper.emitted('request-error')).toHaveLength(1)
expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false)
await wrapper.get('.n-alert button').trigger('click')
await flushPromises()
expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}])
expect(wrapper.find('.n-alert').exists()).toBe(false)
expect(wrapper.text()).toContain('Recovered')
} finally {
wrapper.unmount()
}
})
it('can paginate local data without requiring a request or a row key function', async () => {
const data = [
{ id: 1, name: 'First' },
{ id: 2, name: 'Second' },
]
const wrapper = mount(RTablePro, {
props: { columns, data, pageSize: 1, 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
await instance.setPage(2)
expect(wrapper.text()).toContain('Second')
} finally {
wrapper.unmount()
}
})
it('renders bare data without a toolbar or pagination by default', () => {
const wrapper = mount(RTablePro, {
props: { bare: true, columns, data: response('Bare row', 1).data },
})
try {
expect(wrapper.text()).toContain('Bare row')
expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false)
expect(wrapper.find('header').exists()).toBe(false)
} finally {
wrapper.unmount()
}
})
it('submits the search and resets the page without requiring form state in the caller', async () => {
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const wrapper = mount(RTablePro, {
props: {
columns,
request,
search: [{ key: 'name', label: 'Name' }],
tool: false,
},
})
try {
const instance = wrapper.vm as unknown as TableProInst
await instance.setPage(2)
await wrapper.get('input').setValue(' Alice ')
expect(request).toHaveBeenCalledTimes(2)
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(request).toHaveBeenCalledTimes(3)
expect(request.mock.lastCall?.[0]).toEqual({
name: 'Alice',
page: 1,
pageSize: 10,
})
await wrapper.get('form button[type="button"]').trigger('click')
await flushPromises()
expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 })
} finally {
wrapper.unmount()
}
})
it('enables the table body scroller with a single autoHeight prop', () => {
const wrapper = mount(RTablePro, {
props: {
autoHeight: true,
columns,
data: response('Row', 1).data,
tool: false,
},
})
try {
expect(wrapper.getComponent(NDataTable).props('flexHeight')).toBe(true)
expect(wrapper.classes()).toContain('r-table--fill')
} finally {
wrapper.unmount()
}
})
it('returns to the last available remote page when the total shrinks', async () => {
const request = vi
.fn(async (_params: TableProParams) => response('First page', 5))
.mockResolvedValueOnce(response('Initial', 30))
.mockResolvedValueOnce({ data: [], total: 5 })
const wrapper = mount(RTablePro, { props: { columns, request, tool: false } })
try {
await flushPromises()
const instance = wrapper.vm as unknown as TableProInst
await instance.setPage(3)
expect(request.mock.calls.map(([params]) => params.page)).toEqual([1, 3, 1])
expect(wrapper.text()).toContain('First page')
} finally {
wrapper.unmount()
}
})
it('passes native pagination settings and totals through for a manually controlled remote table', async () => {
const onUpdatePage = vi.fn()
const wrapper = mount(RTablePro, {
props: {
columns,
remote: true,
data: [{ id: 1, name: 'Loaded by caller' }],
pagination: {
page: 3,
pageSize: 20,
itemCount: 80,
showQuickJumper: true,
onUpdatePage,
},
tool: false,
},
})
try {
const pager = wrapper.getComponent(NPagination)
expect(pager.props()).toMatchObject({
page: 3,
pageSize: 20,
itemCount: 80,
showQuickJumper: true,
})
await pager.findAll('.n-pagination-item--button').at(-1)!.trigger('click')
expect(onUpdatePage).toHaveBeenCalledOnce()
expect(onUpdatePage).toHaveBeenCalledWith(4)
} finally {
wrapper.unmount()
}
})
it('uses native initial paging options with managed requests and validates imperative values', async () => {
const request = vi.fn(async (_params: TableProParams) =>
response('Loaded', 100),
)
const wrapper = mount(RTablePro, {
props: {
columns,
request,
pagination: { defaultPage: 2, defaultPageSize: 20 },
tool: false,
},
})
try {
await flushPromises()
const instance = wrapper.vm as unknown as TableProInst
await instance.setPage(0)
await instance.setPageSize(Number.NaN)
expect(request.mock.calls.map(([params]) => params)).toEqual([
{ page: 2, pageSize: 20 },
])
} finally {
wrapper.unmount()
}
})
it('keeps TablePro state in sync when DataTable changes its page directly', async () => {
const data = [
{ id: 1, name: 'First' },
{ id: 2, name: 'Second' },
]
const onUpdatePage = vi.fn()
const wrapper = mount(RTablePro, {
props: { data, columns, pageSize: 1, onUpdatePage, tool: false },
})
try {
const instance = wrapper.vm as unknown as TableProInst
instance.getTableInstance()?.page(2)
await wrapper.vm.$nextTick()
expect(wrapper.getComponent(NPagination).props('page')).toBe(2)
expect(wrapper.text()).toContain('Second')
expect(onUpdatePage).toHaveBeenCalledOnce()
} finally {
wrapper.unmount()
}
})
it('supports an optional title slot for actions without putting controls inside a heading', () => {
const wrapper = mount(RTablePro, {
props: {
columns,
data: [{ id: 1, name: 'Alice' }],
title: 'Default title',
tool: false,
},
slots: { title: '<button>Quick action</button>' },
})
try {
expect(wrapper.get('header button').text()).toBe('Quick action')
expect(wrapper.find('header h2').exists()).toBe(false)
expect(wrapper.text()).not.toContain('Default title')
} finally {
wrapper.unmount()
}
})

View File

@ -1,8 +1,9 @@
import { shallowMount } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { h } from 'vue'
import { h, nextTick } from 'vue'
import Layout from '../../src/layout'
import { router } from '../../src/router'
import { piniaRuntimeStore } from '../../src/store/modules/runtime'
import { piniaSettingStore } from '../../src/store/modules/setting'
it('lets a custom header replace the complete default header and top navigation', () => {
@ -32,3 +33,35 @@ it('lets a custom header replace the complete default header and top navigation'
disposePinia(pinia)
}
})
it('offers a restore button for custom content and also exits with Escape', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const runtime = piniaRuntimeStore()
const wrapper = shallowMount(Layout, {
global: { renderStubDefaultSlot: true, plugins: [router, pinia] },
slots: {
default: () => h('div', { 'data-test': 'custom-content' }, 'Custom'),
},
})
try {
expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe(
false,
)
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true)
await wrapper.get('.r-layout-content-restore__button').trigger('click')
expect(runtime.layoutContentMaximize).toBe(false)
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
expect(runtime.layoutContentMaximize).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})

View File

@ -1,21 +1,52 @@
import { tableMock } from '../../mock/shared/database'
import { listPeople } from '@/demo-data/people'
describe('tableMock', () => {
it('preserves the person response fields after the data generator upgrade', () => {
const person = tableMock({ source: 'demo' })
describe('person demo data', () => {
it('serves consistent, non-overlapping pages with the documented record shape', () => {
const first = listPeople({ page: 1, pageSize: 10 })
const second = listPeople({ page: 2, pageSize: 10 })
expect(person).toMatchObject({
source: 'demo',
id: expect.any(String),
address: expect.any(String),
email: expect.any(String),
expect(first.total).toBe(100)
expect(second.total).toBe(100)
expect(first.data).toHaveLength(10)
expect(second.data).toHaveLength(10)
expect(first.data[0]).toMatchObject({
id: expect.stringMatching(/^[0-9a-f-]{36}$/i),
name: expect.any(String),
email: expect.stringContaining('@'),
address: expect.any(String),
age: expect.any(Number),
createDate: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),
})
expect(person.id).toMatch(/^[0-9a-f-]{36}$/i)
expect(person.age).toBeGreaterThanOrEqual(18)
expect(person.age).toBeLessThanOrEqual(60)
expect(person.email).toContain('@')
expect(
new Set([...first.data, ...second.data].map(({ id }) => id)).size,
).toBe(20)
expect(listPeople({ page: 1, pageSize: 10 })).toEqual(first)
})
it('filters all rows before paginating and reports the filtered total', () => {
const { data } = listPeople()
const person = data.at(-1)!
const email = person.email.toUpperCase()
const matches = data.filter((row) => row.email === person.email)
expect(listPeople({ email, page: 1, pageSize: 1 })).toMatchObject({
data: matches.slice(0, 1),
total: matches.length,
})
expect(
listPeople({ email: 'no such email', page: 1, pageSize: 10 }),
).toMatchObject({
data: [],
total: 0,
})
})
})
it('sorts the complete filtered data before splitting into pages', () => {
const first = listPeople({ page: 1, pageSize: 10, sortAge: 'descend' })
const second = listPeople({ page: 2, pageSize: 10, sortAge: 'descend' })
const ages = [...first.data, ...second.data].map(({ age }) => age)
expect(ages).toEqual([...ages].sort((a, b) => b - a))
expect(first.total).toBe(100)
})

View File

@ -16,7 +16,7 @@ Ray Template 是前端中后台模板,包含可运行的组件与路由示例
| 权限与守卫 | `src/router/utils/vue-router-register.ts`、`src/router/utils/permission.ts` | 同时检查菜单显示与实际导航;前端权限不能替代后端授权 |
| 全局状态 | `src/store/modules`、`src/store/hooks` | [Store 文档](../src/store/README.md),持久化配置使用 `pick`/`omit` |
| 请求与接口 | `src/api`、`src/axios` | [请求文档](../src/axios/README.md),请求/响应拦截器分开注册 |
| 演示接口 | `mock/demo`、`mock/shared` | `vite-plugin-mock-dev-server`,生产环境按实际后端切换 |
| 演示接口 | `mock/demo`、`src/demo-data` | `vite-plugin-mock-dev-server`,生产环境按实际后端切换 |
| 通用组件 | `src/components/base`、`src/components/pro` | 组件、props、types、hook、样式放在同一功能目录 |
| 模板绑定组件 | `src/app-components` | [组件说明](../src/app-components/README.md) |
| 公共工具 | `src/utils` | [分包、兼容入口和测试](../src/utils/README.md) |

View File

@ -44,6 +44,7 @@
- Vitest 测试只复用 Vue/TSX 与自动导入转换,不启动 Mock 服务、HTML 注入、图标扫描或压缩插件。修复遗漏 `await` 的断言,更新水印/全屏用例中的过期预期,保留行为断言。
- 既有颜色转换回归暴露 rgba 空格不一致与八位 hex 透明度丢失,已修正;图表异常保留原始 `cause`。
- Mock.js 存在未修复的原型污染公告,且包含直接 `eval`;替换为 Faker 的中文实例,保持人员字段、分页接口和表格示例能力。新版 Mock 插件的 include 相对 `dir` 匹配,修正原先重复的 `mock/` 前缀并等待首次加载,实际验证了 API 响应。
- 开发时打开 `#/tables/remote`,在 Network 的 Fetch/XHR 分类查看 `GET /api/list?page=1&pageSize=10`。接口使用站点根路径 `/api/list`,不带 `/ray-template/`。Vite 按启动日志中的实际端口访问;静态构建的页面使用同一套本地示例生成逻辑,不依赖 Mock 服务器。
- 浏览器构建和 Autoprefixer 统一到 Vite 8 Baseline Widely Available。开发服务默认 loopback,局域网访问需显式 `--host`。监听排除全部构建目录和 `.ai-local`,避免构建报告时触发页面重复重载。
- CI 与 Docker 使用同一 Node/pnpm,冻结锁文件安装。CI 合并重复流程并覆盖类型、lint、格式、测试、构建;保留检查通过后部署 `main` 到 `dist` 分支的行为。

View File

@ -8,6 +8,7 @@
- `src/styles/base.scss` 是全局样式入口,`design-system.scss` 管理主题变量与基础焦点样式,`setting.scss` 管理布局尺度。`naive.scss` 仅维护模板通用的控件默认值;布局与组件内部规则放在对应组件目录,避免影响嵌套的 Naive UI 实例。
- 控件通常为 8px 圆角、卡片为 12px;页面区块间距使用 20–28px。强调色用于选择与主要操作,正文、说明、眉题使用不同文字层级。
- 顶栏、标签栏和侧栏使用轻分割线,不叠加区域阴影;少量内容卡片使用两层轻阴影。
- 内容最大化时,布局提供置顶的退出操作,使用按钮或 Esc 恢复。
- 页面标题复用 `AppPageHeader`:眉题、一个主标题、简短说明与可选操作区。不要以大段说明或同等权重的卡片标题代替页面层级。
## 页面组织

View File

@ -35,7 +35,7 @@
},
"api": {
"description": "API、Axios 拦截器与演示 Mock",
"paths": ["src/api", "src/axios/README.md", "mock/demo", "mock/shared"],
"paths": ["src/api", "src/axios/README.md", "mock/demo", "src/demo-data"],
"tests": ["__test__/axios/", "__test__/mock/"]
},
"icons": {

View File

@ -1,41 +1,19 @@
import { tableMock } from '@mock/shared/database'
import { array, pagination, response, stringify } from '@mock/shared/utils'
import { listPeople } from '@/demo-data/people'
import { defineMock } from 'vite-plugin-mock-dev-server'
export const getPersonList = defineMock({
export default defineMock({
url: '/api/list',
method: 'GET',
delay: 500,
response: (req, res) => {
const {
query: { page, pageSize, email },
} = req
let list = array(100).map(() => tableMock())
let length = list.length
if (!page || !pageSize) {
res.end(
stringify(
response(list, 200, '请求成功', {
total: length,
}),
),
)
} else {
list = pagination(page, pageSize, list)
if (email) {
list = list.filter((curr) => curr.email.includes(email))
length = list.length
}
res.end(
stringify(
response(list, 200, '请求成功', {
total: length,
}),
),
)
}
},
delay: 250,
body: ({ query }) =>
listPeople({
page: Number(query.page),
pageSize: Number(query.pageSize),
email: typeof query.email === 'string' ? query.email : void 0,
name: typeof query.name === 'string' ? query.name : void 0,
sortAge:
query.sortAge === 'ascend' || query.sortAge === 'descend'
? query.sortAge
: void 0,
}),
})

View File

@ -1,19 +0,0 @@
import { faker } from '@faker-js/faker/locale/zh_CN'
/**
*
* @param option 自定义配置
*
* 基础表格数据
*/
export function tableMock(option?: object) {
return {
...option,
id: faker.string.uuid(),
address: faker.location.state() + faker.location.city(),
email: faker.internet.email(),
name: faker.person.fullName(),
age: faker.number.int({ min: 18, max: 60 }),
createDate: faker.date.past().toISOString().slice(0, 10),
}
}

View File

@ -1,57 +0,0 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export function array(length: number) {
return new Array(length).fill(0)
}
/**
*
* @param pageCurrent 当前页码
* @param pageSize 分页展示条数
* @param array 数据
*
* mock 分页展示数据
*/
export function pagination<T = any>(
pageCurrent: number,
pageSize: number,
array: T[],
): T[] {
const offset = (pageCurrent - 1) * Number(pageSize)
return offset + Number(pageSize) >= array.length
? array.slice(offset, array.length)
: array.slice(offset, offset + Number(pageSize))
}
/**
*
* @param value 原始数据
*
* 格式化数据为 json 格式
*/
export function stringify<T = unknown>(value: T) {
return JSON.stringify(value)
}
/**
*
* @param res 数据
* @param code 响应码
* @param msg 响应信息
*/
export function response<T = any>(
res: T,
code: number,
msg: string,
params?: object,
) {
const basic = {
code,
msg,
data: res,
...params,
}
return basic
}

View File

@ -1,26 +1,24 @@
import { request } from '@/axios'
import type { Person, PersonListParams } from '@/demo-data/people'
import type { PaginationResponse } from '@/types'
export interface MockListParams {
page: number
pageSize: number
}
export type { Person, PersonListParams } from '@/demo-data/people'
export interface Person {
name: string
id: string
age: number
address: string
createDate: string
email: string | null
}
export const getPersonList = (
params: Partial<Pick<MockListParams & Person, 'email' | 'pageSize' | 'page'>>,
export const getPersonList = async (
params: PersonListParams,
signal?: AbortSignal,
) => {
return request<PaginationResponse<Person[]>>({
url: '/api/list',
method: 'get',
params,
})
if (import.meta.env.DEV) {
return request<PaginationResponse<Person[]>>({
url: '/api/list',
method: 'get',
params,
signal,
cancelConfig: { cancel: !signal },
})
}
const { listPeople } = await import('@/demo-data/people')
return listPeople(params)
}

View File

@ -7,7 +7,7 @@
- `RCollapseGrid` 基于 Naive UI Grid,子项需要使用 `NGridItem`;折叠表单 `RCollapse` 的表单项需要使用 `NFormItemGi` / `NGridItem`。不要用普通容器替代 Grid 子项。
- `RChart` 与 `useChart` 负责实例初始化、销毁、尺寸与主题同步;调用方维护 ECharts options,需要的图表与组件按现有 ECharts 注册方式引入。
- `PageResult` 基于 Naive UI Result,可作为组件或错误页面使用,保留继承的 props 与 slots。
- `RTable` 的列顺序配置以第一层列为单位,深层子列跟随根列;大量列数据的性能需按实际业务验证。
- [TablePro](base/RTablePro/README.md) 统一支持纯表格、搜索与分页及自适应高度。列顺序配置以第一层列为单位,深层子列跟随根列。
- `RIcon.name` 为生成的完整分包路径类型,图标改动会在开发、HMR 和构建时同步;不要手工修改生成清单。
组件样式随组件入口加载。调整 Naive UI 内部元素时,使用当前组件的类名限定作用范围;组件需填满容器时由调用处或组件自身声明尺寸。全屏 `RModal` 的卡片正文仅在溢出时滚动,`RBarcode` 的加载区域随条码尺寸或响应式容器伸缩。

View File

@ -1,13 +0,0 @@
import type { ExtractPublicPropTypes } from 'vue'
import useCheckedRowKeys from './src/hooks/useCheckedRowKeys'
import type { UseCheckedRowKeysReturn } from './src/hooks/useCheckedRowKeys'
import useTable from './src/hooks/useTable'
import type { UseTableReturn } from './src/hooks/useTable'
import tableProps from './src/props'
import RTable from './src/Table'
import type * as RTableType from './src/types'
export type TableProps = ExtractPublicPropTypes<typeof tableProps>
export type { RTableType, UseTableReturn, UseCheckedRowKeysReturn }
export { RTable, tableProps, useTable, useCheckedRowKeys }

View File

@ -1,391 +0,0 @@
import './index.scss'
import type { ComponentSize } from '@/types'
import { call, completeSize, renderNode, uuid } from '@/utils'
import { pick } from 'lodash-es'
import { NCard, NDataTable, NDropdown, NFlex } from 'naive-ui'
import type { DataTableProps, DropdownOption } from 'naive-ui'
import { useTemplateRef } from 'vue'
import C from './components/C'
import Fullscreen from './components/Fullscreen'
import Print from './components/Print'
import TablePropsSelect from './components/Props'
import Size from './components/Size'
import props from './props'
import { config } from './shared'
import type {
C as CType,
PropsComponentPopselectKeys,
RTableInst,
} from './types'
export default defineComponent({
name: 'RTable',
inheritAttrs: false,
props,
setup(props, ctx) {
const { expose } = ctx
const rTableInst = useTemplateRef<RTableInst>('rTableInst')
const wrapperRef = useTemplateRef<HTMLElement>('wrapperRef')
const uuidWrapper = uuid(16)
const uuidTable = uuid(16)
/**
*
* x: 横坐标
* y: 纵坐标
* showContextMenu: 是否显示右键菜单
*/
const contextMenuReactive = reactive({
x: 0,
y: 0,
showContextMenu: false,
})
/**
*
* size: table size,内部私有状态管理
*/
const privateReactive = reactive({
size: props.size,
})
const propsPopselectValue = ref(
Object.assign(
{
striped: false,
bordered: false,
},
pick(props, 'striped', 'bordered'),
),
)
// 默认设置 card header style
const cardHeaderStyle = computed(() => {
const { title, tool, cardProps } = props
const { headerStyle = {} } = cardProps ?? {}
if (!title && !tool) {
return Object.assign(
{},
{
paddingTop: '0px',
},
headerStyle,
)
}
return headerStyle
})
// 如果启用了 flexAutoHeight 属性,则自动继承高度
const flexAutoHeightStyle = computed(() => {
const { flexAutoHeight } = props
if (!flexAutoHeight) {
return null
}
return {
height: '100%',
flex: 1,
}
})
/**
*
* @param key 当前选中项的 key
* @param option 当前选中项
*
* @description
* 右键菜单选择事件回调。
*/
const contextMenuSelect = (
key: number | string,
option: DropdownOption,
) => {
contextMenuReactive.showContextMenu = false
const { onContextMenuClick } = props
if (onContextMenuClick) {
call(onContextMenuClick, key, option)
}
}
/**
*
* @param e 鼠标点击事件
*
* @description
* 处理右键菜单事件。
*/
const tableContextMenu = (e: MouseEvent) => {
e.preventDefault()
contextMenuReactive.showContextMenu = false
nextTick().then(() => {
contextMenuReactive.showContextMenu = true
contextMenuReactive.x = e.clientX
contextMenuReactive.y = e.clientY
})
}
/**
*
* @param row 当前行数据
* @param idx 当前行索引
*
* @description
* 合并 RTable 的所有 rowProps,如果开启了右键菜单功能,自动会拦截右键事件。
*/
const combineRowProps = (row: Record<string, unknown>, idx: number) => {
const interceptRowProps = props.rowProps?.(row, idx) || {}
if (props.disabledContextMenu) {
return interceptRowProps
}
return {
...interceptRowProps,
onContextmenu: tableContextMenu,
}
}
/**
*
* @param size 表格尺寸
*
* @description
* 修改表格尺寸。
*/
const changeTableSize = (size: ComponentSize) => {
privateReactive.size = size
}
/**
*
* @param options 表格列配置项
*
* @description
* 更新 table columns,同时触发 onUpdateColumns 和 onUpdate:columns 事件。
*/
const updateTableColumn = (options: CType[]) => {
const { onUpdateColumns, 'onUpdate:columns': $onUpdateColumns } = props
if (onUpdateColumns) {
call(onUpdateColumns, options)
}
if ($onUpdateColumns) {
call($onUpdateColumns, options)
}
}
/**
*
* @description
* 处理自定义的 toolOptions。
* 匹配所有符合条件的 toolOptions,然后执行。
*/
const renderToolOptions = () => {
const { toolOptions } = props
return toolOptions
?.filter(Boolean)
.map((curr) => (typeof curr === 'function' ? curr() : curr))
}
const popselectChange = (value: PropsComponentPopselectKeys[]) => {
const keys = Object.keys(propsPopselectValue.value)
keys.forEach((key) => {
propsPopselectValue.value[
key as keyof typeof propsPopselectValue.value
] = value.includes(key as PropsComponentPopselectKeys)
})
}
/**
*
* @description
* 渲染默认工具栏。
*/
const renderDefaultToolOptions = () => {
const { onUpdateColumns, 'onUpdate:columns': rOnUpdateColumns } = props
const needSettingComponent = !!onUpdateColumns || !!rOnUpdateColumns
return (
<NFlex align="center">
<Print {...props} />
<Size {...props} onChangeSize={changeTableSize} />
<Fullscreen />
{needSettingComponent ? (
<C {...props} onUpdateColumn={updateTableColumn} />
) : null}
<TablePropsSelect
{...props}
onPopselectChange={popselectChange}
onInitialed={popselectChange}
/>
</NFlex>
)
}
/**
*
* @param p props
*
* @description
* 处理 toolOptions,合并渲染所有的 toolOptions。
*/
const tool = (p: typeof props) => {
if (!p.tool) {
return
}
if (!p.toolOptions) {
return renderDefaultToolOptions
}
if (p.coverTool) {
return () => <NFlex align="center">{renderToolOptions()}</NFlex>
}
return () => (
<NFlex align="center">
{renderDefaultToolOptions()}
{renderToolOptions()}
</NFlex>
)
}
onMounted(() => {
// 主动调用 register 方法,满足 useTable 方法正常调用
const { onRegister } = props
if (onRegister && rTableInst.value) {
call(onRegister, rTableInst.value, {
uuidTable,
uuidWrapper,
wrapperRef,
tableRef: rTableInst,
})
}
})
provide(config.tableKey, {
uuidTable,
uuidWrapper,
wrapperRef,
})
expose()
return {
uuidWrapper,
uuidTable,
contextMenuReactive,
rTableInst,
combineRowProps,
contextMenuSelect,
privateReactive,
tool,
wrapperRef,
propsPopselectValue,
cardHeaderStyle,
flexAutoHeightStyle,
tableContextMenu,
}
},
render() {
const {
$props,
$attrs,
$slots,
uuidTable,
contextMenuReactive,
uuidWrapper,
privateReactive,
propsPopselectValue,
cardHeaderStyle,
flexAutoHeightStyle,
} = this
const { class: className, ...restAttrs } = $attrs
const { tool, combineRowProps, contextMenuSelect } = this
const {
renderWrapperHeader,
wrapperBordered,
disabledContextMenu,
contextMenuOptions,
title,
tableFlexHeight,
cardProps,
flexAutoHeight,
flexHeight,
...restProps
} = $props
const { headerStyle, ...restCardProps } = cardProps ?? {}
return (
<NCard
{...restCardProps}
{...{
id: uuidWrapper,
}}
{...restAttrs}
ref="wrapperRef"
bordered={wrapperBordered}
class={className}
// flexAutoHeight 具有更高的优先级
style={Object.assign({}, cardHeaderStyle, flexAutoHeightStyle)}
>
{{
default: () => (
<>
<NDataTable
{...{
id: uuidTable,
}}
{...(restProps as DataTableProps)}
{...propsPopselectValue}
flexHeight={flexAutoHeight ? true : flexHeight}
rowProps={combineRowProps.bind(this)}
size={privateReactive.size}
ref="rTableInst"
style={{
height: flexAutoHeight
? '100%'
: tableFlexHeight !== null && tableFlexHeight !== void 0
? completeSize(tableFlexHeight)
: null,
}}
>
{{
...$slots,
}}
</NDataTable>
{!disabledContextMenu ? (
<NDropdown
show={contextMenuReactive.showContextMenu}
placement="bottom-start"
trigger="manual"
x={contextMenuReactive.x}
y={contextMenuReactive.y}
options={contextMenuOptions}
onClickoutside={() =>
(contextMenuReactive.showContextMenu = false)
}
onSelect={contextMenuSelect.bind(this)}
/>
) : null}
</>
),
header: renderWrapperHeader
? renderNode(title, {
defaultElement: <div style="display: none;"></div>,
})
: null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
'header-extra': tool($props as any),
footer: () => $slots.tableFooter?.(),
action: () => $slots.tableAction?.(),
}}
</NCard>
)
},
})

View File

@ -1,267 +0,0 @@
import { RIcon } from '@/components'
import type { IconName } from '@/icons'
import type { AnyFn, MaybeArray } from '@/types'
import { call } from '@/utils'
import { cloneDeep, isEmpty } from 'lodash-es'
import { NFlex, NPopover, NTree } from 'naive-ui'
import type { TreeDropInfo, TreeOption } from 'naive-ui'
import props from '../props'
import { config } from '../shared'
import type { C } from '../types'
type FixedClick = (type: 'left' | 'right', option: C, index: number) => void
const renderSwitcherIcon = () => (
<RIcon name="action/draggable" size={14} cursor="grab" />
)
const RowIconRender = ({
icon,
title,
onClick,
customClassName,
}: {
icon: IconName
title: string
onClick?: AnyFn
customClassName?: string
}) => {
return (
<NPopover showArrow={false}>
{{
trigger: () => (
<RIcon
name={icon}
size={config.tableIconSize}
cursor="pointer"
customClassName={customClassName}
onClick={onClick?.bind(null)}
/>
),
default: () => title,
}}
</NPopover>
)
}
/**
* 查找节点的兄弟节点和索引
*
* @param node 要查找的节点
* @param nodes 节点列表
* @returns 如果找到节点,则返回包含兄弟节点列表和索引的元组,否则返回 [null, null]
*/
const findSiblingsAndIndex = (
node: TreeOption,
nodes?: TreeOption[],
): [TreeOption[], number] | [null, null] => {
if (!nodes) {
return [null, null]
}
for (let i = 0; i < nodes.length; ++i) {
const siblingNode = nodes[i]
if (siblingNode.key === node.key) {
return [nodes, i]
}
const [siblings, index] = findSiblingsAndIndex(node, siblingNode.children)
if (siblings && index !== null) {
return [siblings, index]
}
}
return [null, null]
}
const R_TABLE_C_TOOL_ICON_ACTIVE = 'r-table__c-tool-icon--active'
export default defineComponent({
name: 'TableC',
props: {
...props,
onUpdateColumn: {
type: [Function, Array] as PropType<MaybeArray<(option: C[]) => void>>,
default: null,
},
},
setup(props) {
let tableColumnType: C
// 深拷贝 columns 避免修改源数据
const treeDataSource = computed({
get: () => {
const cloneColumns = cloneDeep(props.columns).filter((curr) => {
if (curr.type) {
tableColumnType = curr as unknown as C
return false
}
return true
})
return cloneColumns.map((curr, idx) => {
const { key, title, children, fixed, isResizable, ...args } =
curr as C
const isLeftFixedActivated = fixed === 'left'
const isRightFixedActivated = fixed === 'right'
const attr = {
...args,
title,
key,
fixed,
isLeftFixedActivated,
isRightFixedActivated,
isResizable,
}
return {
...attr,
suffix: () => (
<NFlex style="padding-left: 32px;">
<RowIconRender
icon="directional/row_head"
title="固定在列首"
customClassName={
isLeftFixedActivated ? R_TABLE_C_TOOL_ICON_ACTIVE : ''
}
onClick={fixedClick.bind(this, 'left', attr, idx)}
/>
<NPopover showArrow={false}>
{{
trigger: () => (
<RIcon
name="directional/resize_h"
size={config.tableIconSize}
cursor="pointer"
customClassName={
isResizable ? R_TABLE_C_TOOL_ICON_ACTIVE : ''
}
onClick={resizableClick.bind(this, attr, idx)}
/>
),
default: () => '修改列宽',
}}
</NPopover>
<RowIconRender
icon="directional/row_end"
title="固定在列尾"
customClassName={
isRightFixedActivated ? R_TABLE_C_TOOL_ICON_ACTIVE : ''
}
onClick={fixedClick.bind(this, 'right', attr, idx)}
/>
</NFlex>
),
}
}) as C[]
},
set: () => {},
})
const event = (options: C[]) => {
const { onUpdateColumn } = props
if (onUpdateColumn) {
// 使用 nextTick 确保 DOM 更新后再触发事件
nextTick(() => {
call(onUpdateColumn, options)
})
}
}
const resizableClick = (option: C, index: number) => {
option['isResizable'] = !option['isResizable']
option['resizable'] = option['isResizable']
treeDataSource.value[index] = option
event(treeDataSource.value)
}
const fixedClick: FixedClick = (type, option, index) => {
const key = `${type}FixedActivated` as const
const otherKey =
`${type === 'left' ? 'right' : 'left'}FixedActivated` as const
option[otherKey] = false
option[key] = !option[key]
option[key] ? (option['fixed'] = type) : (option['fixed'] = void 0)
treeDataSource.value[index] = option
event(treeDataSource.value)
}
// 拖拽节点的处理函数
const treeDrop = ({ node, dragNode, dropPosition }: TreeDropInfo) => {
const [dragNodeSiblings, dragNodeIndex] = findSiblingsAndIndex(
dragNode,
treeDataSource.value as TreeOption[],
)
if (dragNodeSiblings === null || dragNodeIndex === null) {
return
}
// 从兄弟节点中移除拖拽节点
dragNodeSiblings.splice(dragNodeIndex, 1)
const [nodeSiblings, nodeIndex] = findSiblingsAndIndex(
node,
treeDataSource.value as TreeOption[],
)
if (nodeSiblings === null || nodeIndex === null) {
return
}
// 根据拖拽位置将拖拽节点插入到目标节点的前面或后面
dropPosition === 'before'
? nodeSiblings.splice(nodeIndex, 0, dragNode)
: nodeSiblings.splice(nodeIndex + 1, 0, dragNode)
if (!isEmpty(tableColumnType)) {
nodeSiblings.unshift(tableColumnType as TreeOption)
}
// 触发事件,更新树形数据源
event(nodeSiblings as C[])
}
return {
treeDataSource,
treeDrop,
}
},
render() {
return (
<NPopover displayDirective="show" trigger="click" showArrow={false}>
{{
trigger: () => (
<RIcon
name="action/setting"
size={config.tableIconSize}
cursor="pointer"
customClassName="r-table__setting"
/>
),
default: () => (
<NTree
class="r-table__c-tree"
data={this.treeDataSource as TreeOption[]}
blockLine
draggable
keyboard={false}
labelField="title"
selectable={false}
renderSwitcherIcon={renderSwitcherIcon.bind(this)}
onDrop={this.treeDrop.bind(this)}
/>
),
}}
</NPopover>
)
},
})

View File

@ -1,39 +0,0 @@
import { RIcon } from '@/components'
import { useFullscreen } from 'vue-hooks-plus'
import { config } from '../shared'
import type { TableProvider } from '../types'
export default defineComponent({
name: 'TableFullscreen',
setup() {
const { wrapperRef } = inject<TableProvider>(
config.tableKey,
{} as TableProvider,
)
const [isFullscreen, { toggleFullscreen, isEnabled }] =
useFullscreen(wrapperRef)
return {
toggleFullscreen,
isEnabled,
}
},
render() {
const { toggleFullscreen, isEnabled, $t } = this
return (
<RIcon
name="action/fullscreen"
size={config.tableIconSize}
cursor="pointer"
onClick={() => {
if (!isEnabled) {
window.$message.warning($t('globalMessage.isEnabledFullscreen'))
}
toggleFullscreen()
}}
/>
)
},
})

View File

@ -1,50 +0,0 @@
import { RIcon } from '@/components'
import { printDom } from '@/utils/dom'
import props from '../props'
import { config } from '../shared'
import type { TableProvider } from '../types'
export default defineComponent({
name: 'TablePrint',
props,
setup(props) {
const { wrapperRef } = inject<TableProvider>(
config.tableKey,
{} as TableProvider,
)
const printTableClick = () => {
const {
printTableOptions: { printOptions = {}, domToImageOptions } = {},
title,
} = props
if (
printOptions.documentTitle === '' ||
printOptions.documentTitle === void 0 ||
printOptions.documentTitle === null
) {
printOptions.documentTitle = typeof title === 'string' ? title : ''
}
printDom(wrapperRef, {
printOptions,
domToImageOptions,
})
}
return {
printTableClick,
}
},
render() {
return (
<RIcon
name="action/print"
size={config.tableIconSize}
cursor="pointer"
onClick={this.printTableClick.bind(this)}
/>
)
},
})

View File

@ -1,80 +0,0 @@
import { RIcon } from '@/components'
import type { MaybeArray } from '@/types'
import { call } from '@/utils'
import { NPopselect } from 'naive-ui'
import props from '../props'
import { config, propsOptions } from '../shared'
import type { PropsComponentPopselectKeys } from '../types'
export default defineComponent({
name: 'TablePropsSelect',
props: {
...props,
onPopselectChange: {
type: [Function, Array] as PropType<
MaybeArray<(size: PropsComponentPopselectKeys[]) => void>
>,
default: null,
},
onInitialed: {
type: [Function, Array] as PropType<
MaybeArray<(size: PropsComponentPopselectKeys[]) => void>
>,
default: null,
},
},
setup(props) {
const popoverShow = ref(false)
const propsPopselectValue = ref<PropsComponentPopselectKeys[]>([])
const updatePopselectValue = (value: PropsComponentPopselectKeys[]) => {
const { onPopselectChange } = props
if (onPopselectChange) {
call(onPopselectChange, value)
}
}
const initialPopselectValue = () => {
const { striped, bordered, onInitialed } = props
if (striped) {
propsPopselectValue.value.push('striped')
}
if (bordered) {
propsPopselectValue.value.push('bordered')
}
if (onInitialed) {
call(onInitialed, propsPopselectValue.value)
}
}
initialPopselectValue()
return {
propsPopselectValue,
popoverShow,
updatePopselectValue,
}
},
render() {
return (
<NPopselect
v-model:value={this.propsPopselectValue}
options={propsOptions}
trigger="click"
multiple
onUpdateValue={this.updatePopselectValue.bind(this)}
>
<RIcon
name="directional/expanded"
size={config.tableIconSize}
cursor="pointer"
style="transform: rotate(270deg);"
/>
</NPopselect>
)
},
})

View File

@ -1,66 +0,0 @@
import { RIcon } from '@/components'
import type { ComponentSize, MaybeArray } from '@/types'
import { call } from '@/utils'
import { NPopselect } from 'naive-ui'
import props from '../props'
import { config } from '../shared'
export default defineComponent({
name: 'TableSizeSelect',
props: {
onChangeSize: {
type: [Function, Array] as PropType<
MaybeArray<(size: ComponentSize) => void>
>,
default: null,
},
...props,
},
setup(props) {
const size = ref(props.size)
const sizeOptions = [
{
label: '默认',
value: 'medium',
},
{
label: '紧凑',
value: 'small',
},
{
label: '宽松',
value: 'large',
},
]
const updatePopselectValue = (value: string | number) => {
const { onChangeSize } = props
if (onChangeSize) {
call(onChangeSize, value as ComponentSize)
}
}
return {
size,
sizeOptions,
updatePopselectValue,
}
},
render() {
return (
<NPopselect
v-model:value={this.size}
options={this.sizeOptions}
trigger="click"
onUpdateValue={this.updatePopselectValue.bind(this)}
>
<RIcon
name="action/adjustment"
size={config.tableIconSize}
cursor="pointer"
/>
</NPopselect>
)
},
})

View File

@ -1,361 +0,0 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Recordable } from '@/types'
import { effectDispose } from '@/utils'
import type { DataTableColumns, DataTableSelectionColumn } from 'naive-ui'
import type { MaybeRef } from 'vue'
export type RowKey = string | number
export type Action =
'check' | 'uncheck' | 'checkAll' | 'uncheckAll' | 'multipleCheck'
export interface UseCheckedRowKeysOptions<T = unknown> {
/**
*
* @description
* 绑定在 DataTable 组件的唯一关键字段,用于标识每一行数据。
* 在该组件中,默认使用 key 作为关键字段,你可以通过该属性来自定义。
*/
rowKey: string
/**
*
* @param keys 选中的 keys
* @param rows 选中的 rows
* @param meta 当前操作的元数据
*
* @description
* 每当 keys 变化时,会触发该回调函数。
*/
onChange?: (
keys: RowKey[],
rows: T[],
meta: { row: T | undefined; action: Action },
) => void
}
/**
*
* @param tableData DataTable data
* @param bindRowKey DataTable rowKey
* @param key target key
*
* @description
* 递归查找指定 key 的行数据。
* 因为 DataTable data 允许树结构,所以需要递归查找。
*/
const findRow = (
tableData: Recordable[],
bindRowKey: string,
key: RowKey,
): Recordable | undefined => {
if (!tableData.length) {
return void 0
}
for (const curr of tableData) {
if (curr[bindRowKey] === key) {
return curr
}
if (curr?.children?.length) {
const foundRow = findRow(curr.children, bindRowKey, key)
if (foundRow) {
return foundRow
}
}
}
return void 0
}
const isMultiple = (columns: MaybeRef<DataTableColumns<any> | undefined>) => {
const unrefColumns = unref(columns)
if (unrefColumns) {
const idx = unrefColumns.findIndex((column) => {
const { type, multiple } = column as DataTableSelectionColumn
if (
type === 'selection' &&
(multiple === void 0 || multiple === null || multiple === true)
) {
return true
}
})
return idx !== -1
}
return true
}
const matchRowsBySelectionKeys = <T extends Recordable>(
data: MaybeRef<T[] | undefined>,
keys: RowKey[],
currentRows: MaybeRef<T[]>,
bindRowKey: string,
) => {
const unrefData = unref(data)
if (!unrefData) {
return currentRows
}
return keys.reduce((pre, key) => {
const findByCurrentRows = unref(currentRows).findIndex(
(f) => f[bindRowKey] === key,
)
if (findByCurrentRows !== -1) {
pre.push(unref(currentRows)[findByCurrentRows])
return pre
}
const findByData = unrefData.findIndex((f) => f[bindRowKey] === key)
if (findByData !== -1) {
pre.push(unrefData[findByData])
return pre
}
return pre
}, [] as T[])
}
/**
*
* @param data 当前 DataTable 组件的数据
* @param options 配置项
*
* @description
* 该方法用于便捷的管理 checkedRowKeys。
*
* 该方法依赖 rowKey,该字段用于标识每一行数据,与组件的约定保持一致。
*
* 如果需要该方法去接管 onUpdateCheckedRowKeys 事件,需要手动去注册 checkedRowKeysBind 方法。
* 并且在使用的时候,需要手动绑定 v-model:checkedRowKeys。
*
* @example
* <template>
* <RDataTable
* v-model:checkedRowKeys="checkedRowKeys"
* onUpdateCheckedRowKeys="checkedRowKeysBind"
* :data="data"
* :columns="columns"
* />
* </template>
* <script lang="ts" setup>
* import { useCheckedRowKeys } from '@/components'
*
* const data = ref([{ ...table data }])
* const columns = [{ ...table columns }]
* const [checkedRowKeys, { checkedRowKeysBind }] = useCheckedRowKeys(data, { rowKey: 'key' }, multiple: true)
* </script>
*/
const useCheckedRowKeys = <
T extends Recordable,
C extends DataTableColumns<any>,
>(
data: MaybeRef<T[] | undefined>,
columns: MaybeRef<C | undefined>,
options?: UseCheckedRowKeysOptions<T>,
) => {
const keysRef = ref<RowKey[]>([])
const rowsRef = ref<any[]>([])
const { rowKey: bindRowKey = 'key', onChange } = options || {}
const currentColumnIsMultiple = computed(() => isMultiple(columns))
/**
*
* @param keys 选中 keys 数据
* @param rows 选中 rows 数据
* @param meta 当前选中元数据与操作类型
*
* @description
* 用于绑定 onUpdateCheckedRowKeys 事件。
*/
const bind = (
keys: RowKey[],
rows: Recordable[],
meta: {
row: Recordable | undefined
action: Action
},
) => {
keysRef.value = keys
rowsRef.value = unref(
matchRowsBySelectionKeys(data, keys, rowsRef, bindRowKey),
)
onChange?.(
keys,
rowsRef.value,
meta as {
row: any | undefined
action: Action
},
)
isMultiple(columns)
}
/**
*
* @description
* 获取所有已选择行的 key。
* key 为你手动绑定的唯一关键字段,与 DataTable 组件需要的 rowKey 保持一致。
*/
const getKeys = () => keysRef.value
/**
*
* @description
* 获取所有已选择行的数据。
*/
const getRows = () => rowsRef.value as T[]
/**
*
* @description
* 清理所有已选择行的 key 和 rows。
*/
const clearAll = () => {
keysRef.value = []
rowsRef.value = []
onChange?.(keysRef.value, rowsRef.value, {
row: void 0,
action: 'uncheckAll',
})
}
/**
*
* @param key 需要清理的 key
* @param rowKey 绑定 key 的字段,默认为 'key',与 DataTable 组件需要的 rowKey 保持一致
*
* @description
* 清理指定 key。
*
* 实际上,在 naive ui 中,key 与 rows 是关联起来的。
* 所以,为了避免歧义的存在,当你清理掉某个 key 时,对应的 rows 也会被清理掉。
*/
const clearKey = (key: RowKey) => {
if (key === null || key === void 0) {
return
}
let _row!: Recordable<T>
keysRef.value = keysRef.value.filter((curr) => curr !== key)
rowsRef.value = rowsRef.value.filter((curr) => {
if (curr[bindRowKey] === key) {
_row = curr
return false
}
return true
})
onChange?.(keysRef.value, rowsRef.value, {
row: _row as any,
action: 'uncheck',
})
}
/**
*
* @param keys 选中的 keys
*
* @description
* 选中指定的 keys。
* 当你调用该方法时,会将 keys 与 data 中的 rows 进行比对,将匹配的 rows 添加到已选中的 rows 中。
*
* 如果 multiple 为 false,那么只会选中一个 key;重复的选择,将会以最后一次绑定的 key 为准。
* 所以,如果你需要选中多个 key,需要将 multiple 设置为 true。
*/
const selectKey = (key: RowKey) => {
if (keysRef.value.includes(key)) {
return
}
const multiple = !currentColumnIsMultiple.value && keysRef.value.length >= 1
const row = findRow(unref(data) || [], bindRowKey, key)
multiple ? (keysRef.value = [key]) : keysRef.value.push(key)
if (row) {
multiple ? (rowsRef.value = [row]) : rowsRef.value.push(row)
onChange?.(keysRef.value, rowsRef.value, {
row: row as any,
action: 'check',
})
}
}
/**
*
* @param keys 批量选中的 keys
*
* @description
* 批量选中指定的 keys。
*/
const selectKeys = (keys: RowKey[]) => {
keys.forEach((key) => selectKey(key))
}
/**
*
* @param key 需要切换的 key
*
* @description
* 切换指定 key 的选中状态。
*/
const toggleKey = (key: RowKey) => {
if (keysRef.value.includes(key)) {
clearKey(key)
} else {
selectKey(key)
}
}
/**
*
* @param key 需要检查的 key
*
* @description
* 检查指定 key 是否被选中。
*/
const isKeySelected = (key: RowKey) => {
return keysRef.value.includes(key)
}
effectDispose(() => {
clearAll()
})
return [
keysRef,
{
checkedRows: rowsRef as Ref<T[]>,
checkedRowKeysBind: bind,
getKeys,
getRows,
clearAll,
clearKey,
selectKey,
selectKeys,
toggleKey,
isKeySelected,
},
] as const
}
export type UseCheckedRowKeysReturn = ReturnType<typeof useCheckedRowKeys>
export default useCheckedRowKeys

View File

@ -1,188 +0,0 @@
import { printDom } from '@/utils'
import type { PrintDomOptions } from '@/utils'
import type {
ColumnKey,
CsvOptionsType,
FilterState,
RTableInst,
ScrollToOptions,
SortOrder,
TableProvider,
UseTableRegister,
} from '../types'
/**
*
* @description
* 获取 RTable 实例。
* 让你能够便捷的调用相关的一些已封装方法。
*
* @warning
* 值得注意的是,必须手动调用 register 方法,否则不能正常使用。
* 在使用 相关 hooks 的时候,需要注意生命周期,确保 register 方法已经被调用与表格实例已经被初始化;
* 不要在父组件 create 阶段就去调用 hook,如果需要,请使用 nextTick 包裹。
*
* @example
* defineComponent({
* setup() {
* const [register, { ...Hooks }] = useTable()
*
* return {
* register,
* ...Hooks,
* }
* },
* render() {
* const { register, ...Hooks } = this
*
* return <RTable onRegister={register} />
* },
* })
*/
const useTable = () => {
const tableRef = shallowRef<RTableInst>()
const extraRef = shallowRef<TableProvider>({} as TableProvider)
const register: UseTableRegister = (inst, extraInfo) => {
if (inst) {
tableRef.value = inst
extraRef.value = extraInfo
}
}
/**
*
* @description
* 获取 RTable 实例。
*/
const getTableInstance = () => {
if (!tableRef.value) {
throw new Error(
'[useTable]: table instance is not ready yet. if you are using useTable, please make sure you have called register method in onRegister event.',
)
}
return tableRef.value
}
/**
*
* @description
* 清空所有 filter 状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter
*/
const clearFilters = () => getTableInstance().clearFilters.call(null)
/**
*
* @description
* 清空所有 sort 状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter
*/
const clearSorter = () => getTableInstance().clearSorter.call(null)
/**
*
* @description
* 下载 CSV。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#export-csv.vue
*/
const downloadCsv = (options?: CsvOptionsType) =>
getTableInstance().downloadCsv.call(null, options)
/**
*
* @description
* 设定表格当前的过滤器。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter
*/
const filters = (filters: FilterState | null) =>
getTableInstance().filters.call(null, filters)
/**
*
* @description
* 手动设置 page。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const page = (page: number) => getTableInstance().page.call(null, page)
/**
*
* @description
* 滚动内容。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const scrollTo: ScrollToOptions = (options) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getTableInstance().scrollTo(options as any)
/**
*
* @description
* 设定表格的过滤状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const sort = (columnKey: ColumnKey, order: SortOrder) =>
getTableInstance().sort.call(null, columnKey, order)
/**
*
* @description
* 打印表格。
*/
const print = (options?: PrintDomOptions) => {
const { uuidWrapper } = extraRef.value ?? {}
if (uuidWrapper) {
const tableWrapperElement = document.getElementById(uuidWrapper)
printDom(tableWrapperElement, options)
}
}
/**
*
* @description
* 设定表格的过滤状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const filter = (filters: FilterState | null) =>
getTableInstance().filter.call(null, filters)
/**
*
* @description
* 获取 Table 组件配置。
*/
const getTableConfig = () => extraRef.value
return [
register,
{
getTableInstance,
clearFilters,
clearSorter,
downloadCsv,
filters,
page,
scrollTo,
sort,
print,
filter,
getTableConfig,
},
] as const
}
export type UseTableReturn = ReturnType<typeof useTable>
export default useTable

View File

@ -1,16 +0,0 @@
.r-table__c-tree {
& .n-tree-node-switcher.n-tree-node-switcher--hide {
visibility: visible;
}
& .r-icon {
&.r-table__c-tool-icon--active {
color: var(--r-theme-primary-color);
}
}
}
.r-table__setting:hover {
transform: rotate(180deg);
transition: transform 0.3s var(--r-bezier);
}

View File

@ -1,252 +0,0 @@
import type { MaybeArray, Recordable } from '@/types'
import { dataTableProps } from 'naive-ui'
import type { DataTableColumn, DropdownOption } from 'naive-ui'
import type { PropType, VNode } from 'vue'
import type {
DownloadCsvTableOptions,
PrintTableOptions,
RTableCardProps,
RTableInst,
UseTableRegister,
} from './types'
const props = {
...dataTableProps,
/**
*
* @description
* 当设置表格高度为弹性高度时,手动设置表格的高度。
*
* @default undefined
*/
tableFlexHeight: {
type: [String, Number] as PropType<string | number>,
default: void 0,
},
/**
*
* @description
* 是否渲染外层容器 header,默认渲染。
* 如果配置为 false,则不会显示外层容器的头部。
*
* @default true
*/
renderWrapperHeader: {
type: Boolean,
default: true,
},
/**
*
* @description
* 配置表格外层容器 props,也就是 NCard 的配置项。
*/
cardProps: {
type: Object as PropType<RTableCardProps>,
default: () => ({}),
},
/**
*
* @description
* 是否启用表格工具栏。
*
* 当设置为 false 时,不会显示表格工具栏。不论是否配置了 toolOptions。
*
* @default true
*/
tool: {
type: Boolean,
default: true,
},
/**
*
* @description
* 下载表格配置项。
*
* @default {}
*/
downloadCsvTableOptions: {
type: Object as PropType<DownloadCsvTableOptions>,
default: () => ({}),
},
/**
*
* @description
* 表格标题,支持 VNode。
*
* @default null
*/
title: {
type: [String, Number, Object] as PropType<VNode | string | number>,
default: null,
},
/**
*
* @description
* 自定义工具栏配置项。
*
* @default undefined
*/
toolOptions: {
type: Array as PropType<(VNode | (() => VNode))[]>,
},
/**
*
* @description
* 是否覆盖原工具栏功能按钮。
*
* @default false
*/
coverTool: {
type: Boolean,
default: false,
},
/**
*
* @description
* 右键菜单配置项。
*
* 基于 NDropdown 实现。
*
* @default undefined
*/
contextMenuOptions: {
type: Array as PropType<DropdownOption[]>,
},
/**
*
* @description
* 是否禁用右键菜单。
*
* 如果设置为 false 则不会唤起右键菜单。
*
* @default false
*/
disabledContextMenu: {
type: Boolean,
default: false,
},
/**
*
* @description
* 右键菜单点击事件回调。
*
* 该属性用于配置右键菜单点击事件。
*
* @default null
*/
onContextMenuClick: {
type: [Function, Array] as PropType<
MaybeArray<(key: string | number, option: DropdownOption) => void>
>,
default: null,
},
/**
*
* @description
* 表格容器边框。
*
* 与表格边框为两个不同配置项。
*
* @default true
*/
wrapperBordered: {
type: Boolean,
default: true,
},
/**
*
* @description
* 表格边框。
*
* @default true
*/
bordered: {
type: Boolean,
default: true,
},
/**
*
* @description
* 打印表格配置项。
*
* 基于 dom printDom 实现。
*
* @default {}
*/
printTableOptions: {
type: Object as PropType<PrintTableOptions>,
default: () => ({}),
},
/**
*
* @description
* 双向绑定列表列配置项事件。
*
* 当配置为 v-model:columns 时,或者是单独调用 onUpdateColumns 时,该属性生效。
* 双向绑定语法糖事件。
*
* @default null
*/
onUpdateColumns: {
type: [Function, Array] as PropType<
MaybeArray<(arr: DataTableColumn[]) => void>
>,
default: null,
},
/**
*
* @description
* 双向绑定列表列配置项事件。
*
* 当配置为 v-model:columns 时,或者是单独调用 onUpdateColumns 时,该属性生效。
* 双向绑定语法糖事件。
*
* @default null
*/
'onUpdate:columns': {
type: [Function, Array] as PropType<
MaybeArray<(arr: DataTableColumn[]) => void>
>,
default: null,
},
/**
*
* @description
* 该属性用于启用右键菜单后被 Table 强行代理后的右键点击事件回调。
*
* 当右键菜单不启用时,不生效。只需要使用 rowProps 属性配置右键菜单事件即可。
*
* @default null
*/
onContextmenu: {
type: [Function, Array] as PropType<
MaybeArray<(row: Recordable, index: number, e: MouseEvent) => void>
>,
default: null,
},
/**
*
* @description
* RTable 注册挂载成功后触发的事件。
* 可以结合 useTable 方法中的 register 方法使用,然后便捷的使用 hooks。
*
* @default null
*/
onRegister: {
type: [Function, Array] as PropType<MaybeArray<UseTableRegister>>,
default: null,
},
/**
*
* @description
* 是否自动继承高度。
*
* @default false
*/
flexAutoHeight: {
type: Boolean,
default: false,
},
} as const
export default props

View File

@ -1,15 +0,0 @@
export const config = {
tableIconSize: '18',
tableKey: Symbol('r-table'),
}
export const propsOptions = [
{
label: '斑马条纹',
value: 'striped',
},
{
label: '表格边框',
value: 'bordered',
},
]

View File

@ -1,88 +0,0 @@
import type { Recordable } from '@/types'
import type { PrintDomOptions } from '@/utils/dom'
import type {
CardProps,
DataTableBaseColumn,
DataTableColumn,
DataTableInst,
DropdownDividerOption,
DropdownGroupOption,
DropdownOption,
DropdownRenderOption,
} from 'naive-ui'
import type { CSSProperties, ShallowRef, VNode } from 'vue'
export interface RTableCardProps extends CardProps {
style?: CSSProperties
}
export type TableActionIcon = string | (() => VNode)
export type DropdownMixedOption =
| DropdownOption
| DropdownGroupOption
| DropdownDividerOption
| DropdownRenderOption
export interface DownloadCsvTableOptions {
fileName?: string
keepOriginalData?: boolean
}
export interface PrintTableOptions extends PrintDomOptions {}
export interface TableProvider {
uuidWrapper: string
uuidTable: string
wrapperRef: Readonly<ShallowRef<HTMLElement | null>>
tableRef: Readonly<ShallowRef<RTableInst | null>>
}
export interface C extends DataTableBaseColumn {
leftFixedActivated?: boolean
rightFixedActivated?: boolean
resizable?: boolean
isResizable?: boolean
isLeftFixedActivated?: boolean
isRightFixedActivated?: boolean
children?: C[]
}
export interface RTableInst extends Omit<DataTableInst, 'clearFilter'> {
/**
*
* @description
* 打印表格。
*/
print: (options?: PrintDomOptions) => void
config: TableProvider
}
export type OverridesTableColumn<T = Recordable> = C | DataTableColumn<T>
export interface TableInst extends Omit<TableProvider, 'wrapperRef'> {
rTableInst: RTableInst
}
export type PropsComponentPopselectKeys = 'striped' | 'bordered'
type DownloadCsvParameters = Parameters<RTableInst['downloadCsv']>
export type CsvOptionsType = DownloadCsvParameters[0]
type FiltersParameters = Parameters<RTableInst['filters']>
export type FilterState = FiltersParameters[0]
export type ScrollToOptions = RTableInst['scrollTo']
type SortParameters = Parameters<RTableInst['sort']>
export type ColumnKey = SortParameters[0]
export type SortOrder = SortParameters[1]
export type UseTableRegister = (
tableInst: RTableInst,
extra: TableProvider,
) => void

View File

@ -0,0 +1,66 @@
# TablePro
统一从 `@/components` 导入 `RTablePro`。它沿用 Naive UI 的列、排序、选择和渲染配置;搜索、分页和工具栏按场景启用。
```tsx
import { RTablePro } from '@/components'
// 纯表格:只渲染数据表,默认无工具栏和分页。
<RTablePro bare columns={columns} data={rows} />
// 完整模式:内置搜索,自动加载并分页。
<RTablePro
columns={columns}
request={loadPeople}
search={[{ key: 'email', label: '邮箱' }]}
/>
// 自适应高度:表格填充当前内容区,行在内部滚动。
<RTablePro autoHeight columns={columns} data={rows} />
```
- `data` 用于本地数据;`request(params, signal)` 用于远端数据,返回 `Promise<{ data: Row[]; total: number }>`。`total` 是应用筛选后的总数;传递 `signal` 给 HTTP 客户端可以取消上一条请求。
- 搜索字段有 `key`、`label` 和可选的 `placeholder`、`options`(下拉选项)。输入文字只更新草稿,提交后回到第 1 页。本地文字匹配忽略大小写,下拉按值匹配;远端模式把搜索值传给 `request`。外部筛选可用 `params`,复杂表单可用 `filters` 插槽及其 `submit(values)` 方法。
- 完整模式默认使用 DataTable 底部自带的分页器,每页 10 条。空间不足时使用 Naive UI 的简洁分页,也可通过 `pagination.simple` 指定模式。用 `pageSize`、`pagination={{ pageSizes: [10, 20, 50] }}` 调整,或用 `pagination={false}` 关闭。关闭时请求不附加 `page`、`pageSize`;`bare pagination` 可以单独保留分页。
- 搜索区在结果上方。表格左上方可用 `title` 传文字,或用同名插槽放筛选开关、快捷操作等;都不传时不占位。`toolbar` 插槽和默认工具集中在表格右上方。
- 行标识默认取 `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` 插槽。
迁移时,把旧 `RTable` 改为 `RTablePro bare`(需要完整工具栏时省略 `bare`),把 `useTable` / `useTablePro` 的注册改为可选的实例 ref。旧版 `requestConfig` 可改为 `params` 或请求函数内的字段映射;`takeoverAutoHeight`、`flexAutoHeight` 改为 `autoHeight`。
## 列显示与缓存
只传普通 `columns` 数组,就能在同一套「列设置」里勾选显示、拖动顺序、固定列或启用列宽调整。默认由 TablePro 在当前实例内维护这些操作,不修改传入的数组。想跨刷新记住显示选择时,加一个稳定的表格标识:
```tsx
<RTablePro columns={columns} data={rows} columnStateKey="orders:list" />
```
- 使用 Naive UI 的列 `key`,同一表的列 key 唯一且稳定。勾选状态独立于列定义;列分组会跟随子列,选择列和展开列不会被勾选隐藏。至少保留一个数据列。
- 缓存是按表格标识分隔的本地偏好。只保存隐藏列的 key,启用或切换标识时读一次,用户改动时才写入。新增列默认显示,失效 key 不影响渲染,恢复全部列会清除缓存。不传标识时仅保留实例内状态。需要按账号或租户隔离时,将其标识纳入 key。
- 页面需要接管列顺序、固定位置或 `resizable` 时,可以用 `v-model:columns`;收到的是完整列定义,包含已隐藏的列。显隐始终由列设置维护,固定列仍遵守 Naive UI 的数字列宽约定。
- 不缓存行数据、列定义、回调、列宽、固定或顺序。默认模式用列 key 维护实例内的调整;更新列标题、渲染器等定义不会抹掉用户调整。
## 打印和 CSV
内置打印按当前排序、筛选和分页打印**当前页数据和可见列**。使用单独的白底 HTML 表格,跨纸页重复表头;不打印搜索、操作、复选框、展开区、分页或插槽。虚拟滚动不影响取数。需要特殊单元格文本时用 `formatCell`;未配置时沿用 `getCsvCell` 或字段值。自定义 Vue 单元格、树展开状态和合并格不会复刻为打印布局;需要复刻时指定自定义区域。
```tsx
<RTablePro
columns={columns}
data={rows}
printTableOptions={{ target: reportRef }}
/>
```
内置按钮使用 `printTableOptions`。单次打印可以用 `table.value?.print({ target: reportRef, title: '报表', style: '@page { size: landscape; }' })` 覆盖配置;目标支持元素、ref 或 getter。自定义区域以独立打印文档呈现,可用 `style` 提供专用 CSS,或用 `data-print-ignore` 排除其中的控件。旧版 `printOptions.documentTitle` 改用 `title`,截图配置不再适用。
CSV 默认导出当前页可见数据列;`keepOriginalData` 使用传入的整批数据(远端模式不会为导出额外请求)。`allowExport: false` 排除对应列,`getCsvCell` / `getCsvHeader` 返回原始文本,由组件处理 CSV 转义。
## Naive UI 的配置边界
普通列配置、选择、展开、排序、筛选、汇总、虚拟滚动、固定列、空状态和加载插槽沿用 [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`。
在「表格」菜单下,可分别查看纯表格、远端查询与分页(含服务端排序和错误重试)、自适应高度(含虚拟滚动)、列设置与缓存、默认和自定义打印、插槽与实例操作。旧示例路径会重定向到对应子页。

View File

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

View File

@ -0,0 +1,291 @@
import './index.scss'
import { useI18n } from '@/hooks/template/useI18n'
import { useElementSize } from '@vueuse/core'
import { NDataTable, NDropdown } from 'naive-ui'
import type { DataTableInst, DataTableProps } from 'naive-ui'
import { useTemplateRef } from 'vue'
import { useColumnLayout, useColumnVisibility } from './columns'
import C from './components/C'
import Fullscreen from './components/Fullscreen'
import TablePropsSelect from './components/Props'
import Size from './components/Size'
import ToolButton from './components/ToolButton'
import { buildTableCsv, downloadTableCsv } from './csv'
import {
buildPrintableTable,
printTableContent,
resolvePrintContent,
} from './printing'
import props from './props'
import { config } from './shared'
import type { PropsComponentPopselectKeys, TablePanelInst } from './types'
export default defineComponent({
name: 'TablePanel',
inheritAttrs: false,
props,
setup(props, { attrs, slots, expose }) {
const { t } = useI18n('table')
const table = useTemplateRef<DataTableInst>('dataTable')
const wrapper = useTemplateRef<HTMLElement>('wrapper')
const responsivePager = computed(() =>
typeof props.pagination === 'object' && props.pagination.simple == null
? wrapper.value
: null,
)
const { width } = useElementSize(responsivePager)
const { layoutColumns, reorderColumns, patchColumn } = useColumnLayout(
toRef(props, 'columns'),
toRef(props, 'onUpdate:columns'),
)
const { hiddenKeys, visibleColumns, setColumnVisible, resetColumns } =
useColumnVisibility(layoutColumns, toRef(props, 'columnStateKey'))
const printing = ref(false)
provide(config.wrapperKey, wrapper)
const size = ref(props.size)
const appearance = reactive({
striped: props.striped,
bordered: props.bordered,
})
const context = reactive({ x: 0, y: 0, show: false })
watch(
() => props.size,
(value) => {
size.value = value
},
)
watch(
() => props.striped,
(value) => {
appearance.striped = value
},
)
watch(
() => props.bordered,
(value) => {
appearance.bordered = value
},
)
const handle: TablePanelInst = {
getTableInstance: () => table.value,
downloadCsv: (options) => {
const { fileName, keepOriginalData } = {
...props.downloadCsvTableOptions,
...options,
}
const rows = keepOriginalData
? props.data
: table.value?.getCurrentPageData()
if (rows)
downloadTableCsv(
buildTableCsv(
visibleColumns.value,
rows,
props.getCsvCell,
props.getCsvHeader,
),
fileName,
)
},
print: async (options) => {
if (printing.value || props.loading) return false
const printOptions = {
title: typeof props.title === 'string' ? props.title : '',
formatCell: props.getCsvCell,
formatHeader: props.getCsvHeader,
...props.printTableOptions,
...options,
}
printing.value = true
try {
const content = resolvePrintContent(printOptions, () => {
const rows = table.value?.getCurrentPageData()
return rows
? buildPrintableTable(
document,
visibleColumns.value,
rows,
printOptions,
)
: null
})
return !!content && (await printTableContent(content, printOptions))
} catch (error) {
console.error('[TablePro]: Could not open print preview.', error)
return false
} finally {
printing.value = false
}
},
}
expose(handle)
const rowProps: NonNullable<DataTableProps['rowProps']> = (row, index) => {
const original = props.rowProps?.(row, index)
if (!props.contextMenuOptions?.length) return original ?? {}
return {
...original,
onContextmenu: (event: PointerEvent) => {
original?.onContextmenu?.(event)
if (event.defaultPrevented) return
event.preventDefault()
Object.assign(context, {
x: event.clientX,
y: event.clientY,
show: true,
})
},
}
}
const changeAppearance = (values: PropsComponentPopselectKeys[]) => {
appearance.striped = values.includes('striped')
appearance.bordered = values.includes('bordered')
}
return () => {
const {
bare,
autoHeight,
title,
tool,
contextMenuOptions,
onContextMenuClick,
'onUpdate:columns': updateColumns,
downloadCsvTableOptions,
printTableOptions,
columnStateKey,
pagination,
...dataTableProps
} = props
const {
filters,
title: titleSlot,
toolbar,
notice,
tableFooter,
tableAction,
...dataTableSlots
} = slots
const showToolbar = !bare && (tool || toolbar)
const headerTitle = bare ? null : titleSlot ? (
titleSlot()
) : typeof title === 'string' && title ? (
<h2>{title}</h2>
) : (
title
)
const extras = tableFooter?.()
const actions = tableAction?.()
const mergedPagination =
typeof pagination === 'object' && width.value > 0 && width.value < 600
? { simple: true, ...pagination }
: pagination
return (
<section
{...attrs}
ref="wrapper"
class={['r-table', { 'r-table--fill': autoHeight }, attrs.class]}
>
{filters?.()}
{notice?.()}
<div class="r-table__result">
{headerTitle || showToolbar ? (
<header class="r-table__header">
{headerTitle ? (
<div class="r-table__heading">{headerTitle}</div>
) : null}
{showToolbar ? (
<div class="r-table__toolbar">
{toolbar?.()}
{tool ? (
<>
<ToolButton
icon="action/print"
label={t('print')}
disabled={props.loading || printing.value}
onClick={async () => {
if (!(await handle.print()))
window.$message?.error(t('printError'))
}}
/>
<Size
size={size.value}
onChange={(value) => {
size.value = value
}}
/>
<Fullscreen />
{props.columns.length ? (
<C
columns={layoutColumns.value}
hiddenKeys={hiddenKeys.value}
onReorderColumns={reorderColumns}
onPatchColumn={patchColumn}
onToggleColumn={setColumnVisible}
onResetColumns={resetColumns}
/>
) : null}
<TablePropsSelect
{...appearance}
onChange={changeAppearance}
/>
</>
) : null}
</div>
) : null}
</header>
) : null}
<NDataTable
{...dataTableProps}
{...appearance}
ref="dataTable"
columns={visibleColumns.value}
pagination={mergedPagination}
flexHeight={autoHeight || dataTableProps.flexHeight}
rowProps={rowProps}
size={size.value}
>
{dataTableSlots}
</NDataTable>
</div>
{extras ? <div class="r-table__footer">{extras}</div> : null}
{actions ? <div class="r-table__action">{actions}</div> : null}
{contextMenuOptions?.length ? (
<NDropdown
show={context.show}
placement="bottom-start"
trigger="manual"
x={context.x}
y={context.y}
options={contextMenuOptions}
onClickoutside={() => {
context.show = false
}}
onSelect={(key, option) => {
context.show = false
onContextMenuClick?.(key, option)
}}
/>
) : null}
</section>
)
}
},
})

View File

@ -0,0 +1,297 @@
import { useI18n } from '@/hooks/template/useI18n'
import { call } from '@/utils/vue/call'
import { NAlert, NButton } from 'naive-ui'
import type { PaginationProps } from 'naive-ui'
import type { ExtractPublicPropTypes, PropType } from 'vue'
import Search from './components/Search'
import tableProps from './props'
import TablePanel from './TablePanel'
import type {
TablePanelInst,
TableProParams,
TableProRequest,
TableProResult,
TableProSearchField,
TableSearchValues,
} from './types'
const positiveInteger = (value: number) =>
Number.isSafeInteger(value) && value > 0
const props = {
...tableProps,
pagination: {
type: [Boolean, Object] as PropType<boolean | PaginationProps>,
default: void 0,
},
pageSize: { type: Number, default: 10 },
request: Function as PropType<TableProRequest>,
params: Object,
search: Array as PropType<TableProSearchField[]>,
rowKey: {
type: tableProps.rowKey,
default: (row: { id?: string | number; key?: string | number }) =>
row.id ?? row.key,
},
}
export type TableProProps = ExtractPublicPropTypes<typeof props>
export interface TableProInst extends TablePanelInst {
reload: (resetPage?: boolean) => Promise<void>
setPage: (page: number) => Promise<void>
setPageSize: (pageSize: number) => Promise<void>
}
export default defineComponent({
name: 'RTablePro',
inheritAttrs: false,
props,
emits: { 'request-error': (_error: unknown) => true },
setup(props, { attrs, slots, expose, emit }) {
const { t } = useI18n('table')
const table = shallowRef<TablePanelInst>()
const result = shallowRef<TableProResult>({ data: [], total: 0 })
const loading = ref(false)
const failed = ref(false)
const searchValues = shallowRef<TableSearchValues>({})
const pagination = computed(() => props.pagination ?? !props.bare)
const pagerOptions = computed(() =>
typeof props.pagination === 'object' ? props.pagination : void 0,
)
const configuredPageSize = computed(() => {
const size =
pagerOptions.value?.pageSize ??
pagerOptions.value?.defaultPageSize ??
props.pageSize
return positiveInteger(size) ? size : 10
})
const firstPage = pagerOptions.value?.defaultPage ?? 1
const page = ref(positiveInteger(firstPage) ? firstPage : 1)
const pageSize = ref(configuredPageSize.value)
const localRows = computed(() => {
const entries = Object.entries(searchValues.value)
if (!entries.length) return props.data
const selects = new Set(
props.search?.filter(({ options }) => options).map(({ key }) => key),
)
return props.data.filter((row) =>
entries.every(([key, value]) => {
const cell = row[key]
return typeof value === 'number' || selects.has(key)
? cell === value
: String(cell ?? '')
.toLowerCase()
.includes(value.toLowerCase())
}),
)
})
let pending: AbortController | undefined
const reload = async (resetPage = false) => {
if (resetPage) page.value = 1
pending?.abort()
failed.value = false
const { request, params } = props
if (!request) {
pending = void 0
loading.value = false
return
}
const current = new AbortController()
pending = current
loading.value = true
// 分页字段由表格统一管理,筛选参数不能覆盖当前页码。
const query: TableProParams = { ...params, ...searchValues.value }
if (pagination.value !== false) {
query.page = page.value
query.pageSize = pageSize.value
} else {
delete query.page
delete query.pageSize
}
try {
const response = await request(query, current.signal)
// 快速切页或筛选时,只接收最后一次请求的结果。
if (current.signal.aborted) return
if (
!Array.isArray(response.data) ||
!Number.isSafeInteger(response.total) ||
response.total < 0
) {
throw new TypeError(
'[RTablePro] Expected { data: Row[], total: number }.',
)
}
const lastPage = Math.max(1, Math.ceil(response.total / pageSize.value))
if (pagination.value !== false && page.value > lastPage) {
page.value = lastPage
if (response.total) {
await reload()
return
}
}
result.value = response
} catch (error) {
if (current.signal.aborted) return
failed.value = true
emit('request-error', error)
} finally {
if (pending === current) {
pending = void 0
loading.value = false
}
}
}
const setPage = async (value: number) => {
if (!positiveInteger(value) || page.value === value) return
page.value = value
await reload()
}
const setPageSize = async (value: number) => {
if (!positiveInteger(value) || pageSize.value === value) return
pageSize.value = value
await reload(true)
}
const submitSearch = (values: TableSearchValues) => {
searchValues.value = values
return reload(true)
}
watch(
[
() => props.request,
() => props.params,
() => pagination.value === false,
configuredPageSize,
],
(_values, previous) => {
void reload(previous.length > 0)
},
{ deep: true, immediate: true },
)
watch(
configuredPageSize,
(value) => {
pageSize.value = value
},
{ flush: 'sync' },
)
onBeforeUnmount(() => {
pending?.abort()
pending = void 0
})
const instance: TableProInst = {
reload,
setPage,
setPageSize,
getTableInstance: () => table.value?.getTableInstance() ?? null,
print: (options) => table.value?.print(options) ?? Promise.resolve(false),
downloadCsv: (options) => table.value?.downloadCsv(options),
}
expose(instance)
return () => {
const {
request,
params,
pagination: _pagination,
pageSize: _pageSize,
search,
loading: externalLoading,
remote,
onUpdatePage,
onUpdatePageSize,
...rest
} = props
const options = pagerOptions.value
const { filters, error, notice, ...panelSlots } = slots
const paginationProps: false | PaginationProps =
pagination.value === false
? false
: {
showSizePicker: true,
pageSizes: [10, 20, 50, 100],
prefix: ({ itemCount }) => t('total', { count: itemCount }),
...options,
page: request ? page.value : (options?.page ?? page.value),
pageSize: request
? pageSize.value
: (options?.pageSize ?? pageSize.value),
...(request
? { itemCount: result.value.total, pageCount: void 0 }
: {}),
}
return (
<TablePanel
{...attrs}
{...rest}
ref={table}
remote={!!request || remote}
data={request ? result.value.data : localRows.value}
loading={loading.value || externalLoading}
pagination={paginationProps}
onUpdatePage={(value) => {
void setPage(value)
if (onUpdatePage) call(onUpdatePage, value)
}}
onUpdatePageSize={(value) => {
void setPageSize(value)
if (onUpdatePageSize) call(onUpdatePageSize, value)
}}
>
{{
...panelSlots,
filters: filters
? () => filters({ submit: submitSearch })
: search?.length
? () => <Search fields={search} onSearch={submitSearch} />
: void 0,
notice: () =>
failed.value
? (error?.({ reload }) ?? (
<NAlert type="error" title={t('requestError')}>
<NButton size="small" secondary onClick={() => reload()}>
{t('retry')}
</NButton>
</NAlert>
))
: notice?.(),
}}
</TablePanel>
)
}
},
})

View File

@ -0,0 +1,201 @@
import { getStorage, removeStorage, setStorage } from '@/utils/cache'
import type { DataTableColumn } from 'naive-ui'
import type { Ref } from 'vue'
export type TableColumnKey = string | number
export type KeyedColumn = Extract<DataTableColumn, { key: TableColumnKey }>
export type LeafColumn = Exclude<KeyedColumn, { children: DataTableColumn[] }>
export type ColumnLayoutPatch = Partial<
Pick<KeyedColumn, 'fixed' | 'resizable'>
>
export const hasColumnKey = (column: DataTableColumn): column is KeyedColumn =>
'key' in column
export const getLeafColumns = (columns: DataTableColumn[]): LeafColumn[] =>
columns.flatMap((column) =>
!hasColumnKey(column)
? []
: 'children' in column
? getLeafColumns(column.children)
: [column],
)
const applyRootOrder = (
columns: DataTableColumn[],
order: TableColumnKey[],
) => {
const orderedKeys = new Set(order)
const byKey = new Map(
columns.filter(hasColumnKey).map((column) => [column.key, column]),
)
const ordered = order.flatMap((key) => byKey.get(key) ?? [])
let index = 0
// 新列和选择/展开列保留输入的位置,已有列按 key 恢复顺序。
return columns.map((column) =>
hasColumnKey(column) && orderedKeys.has(column.key)
? ordered[index++]
: column,
)
}
export const useColumnLayout = (
columns: Ref<DataTableColumn[]>,
onUpdate: Ref<((columns: DataTableColumn[]) => void) | undefined>,
) => {
const order = shallowRef<TableColumnKey[]>()
const patches = shallowRef<Map<TableColumnKey, ColumnLayoutPatch>>()
const layoutColumns = computed(() => {
if (onUpdate.value) return columns.value
const arranged = order.value
? applyRootOrder(columns.value, order.value)
: columns.value
const adjustments = patches.value
if (!adjustments?.size) return arranged
return arranged.map((column) => {
const patch = hasColumnKey(column) && adjustments.get(column.key)
return patch ? { ...column, ...patch } : column
})
})
const reorderColumns = (keys: TableColumnKey[]) => {
if (onUpdate.value) {
onUpdate.value(applyRootOrder(columns.value, keys))
} else {
order.value = keys
}
}
const patchColumn = (key: TableColumnKey, patch: ColumnLayoutPatch) => {
if (onUpdate.value) {
onUpdate.value(
columns.value.map((column) =>
hasColumnKey(column) && column.key === key
? { ...column, ...patch }
: column,
),
)
} else {
const next = new Map(patches.value)
next.set(key, { ...next.get(key), ...patch })
patches.value = next
}
}
return { layoutColumns, reorderColumns, patchColumn }
}
const filterColumns = (
columns: DataTableColumn[],
hidden: ReadonlySet<TableColumnKey>,
): DataTableColumn[] => {
const filtered = columns.flatMap((column): DataTableColumn[] => {
if (!hasColumnKey(column)) return [column]
if (!('children' in column)) return hidden.has(column.key) ? [] : [column]
const children = column.children.filter((child) => !hidden.has(child.key))
if (!children.length) return []
return [
children.length === column.children.length
? column
: { ...column, children },
]
})
return filtered.length === columns.length &&
filtered.every((column, index) => column === columns[index])
? columns
: filtered
}
const storageKey = (key?: string) => {
const scope = key?.trim()
return scope ? `table-pro:columns:v1:${scope}` : ''
}
const storageOptions = { prefix: true } as const
const isColumnKey = (value: unknown): value is TableColumnKey =>
typeof value === 'string' ||
(typeof value === 'number' && Number.isFinite(value))
export const useColumnVisibility = (
columns: Ref<DataTableColumn[]>,
scope: Ref<string | undefined>,
) => {
const hidden = shallowRef(new Set<TableColumnKey>())
const keys = computed(() => [
...new Set(getLeafColumns(columns.value).map(({ key }) => key)),
])
watch(
() => storageKey(scope.value),
(key) => {
const stored = key
? getStorage<unknown>(key, 'localStorage', storageOptions)
: null
hidden.value = new Set(
Array.isArray(stored) ? stored.filter(isColumnKey) : [],
)
},
{ immediate: true },
)
const hiddenKeys = computed(() => {
if (!hidden.value.size) return hidden.value
const active = new Set(keys.value.filter((key) => hidden.value.has(key)))
// 列定义动态收缩时,至少保留一个可用的数据列。
if (active.size && active.size === keys.value.length)
active.delete(keys.value[0])
return active
})
const visibleColumns = computed(() =>
hiddenKeys.value.size
? filterColumns(columns.value, hiddenKeys.value)
: columns.value,
)
const visibleCount = computed(() => keys.value.length - hiddenKeys.value.size)
const persist = (next: Set<TableColumnKey>) => {
hidden.value = next
const key = storageKey(scope.value)
if (!key) return
if (next.size) setStorage(key, [...next], 'localStorage', storageOptions)
else removeStorage(key, 'localStorage', storageOptions)
}
const setColumnVisible = (key: TableColumnKey, visible: boolean) => {
if (!keys.value.includes(key) || visible !== hiddenKeys.value.has(key))
return
if (!visible && visibleCount.value <= 1) return
const next = new Set(hiddenKeys.value)
if (visible) next.delete(key)
else next.add(key)
persist(next)
}
const resetColumns = () => {
if (hidden.value.size) persist(new Set())
}
return { hiddenKeys, visibleColumns, setColumnVisible, resetColumns }
}

View File

@ -0,0 +1,191 @@
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NFlex, NPopover, NTree } from 'naive-ui'
import type { TreeDropInfo, TreeOption } from 'naive-ui'
import type { PropType } from 'vue'
import { getLeafColumns, hasColumnKey } from '../columns'
import type { ColumnLayoutPatch, KeyedColumn, TableColumnKey } from '../columns'
import props from '../props'
import ToolButton from './ToolButton'
export default defineComponent({
name: 'TableColumns',
props: {
columns: props.columns,
hiddenKeys: {
type: Object as PropType<ReadonlySet<TableColumnKey>>,
required: true,
},
},
emits: {
reorderColumns: (_keys: TableColumnKey[]) => true,
patchColumn: (_key: TableColumnKey, _patch: ColumnLayoutPatch) => true,
toggleColumn: (_key: TableColumnKey, _visible: boolean) => true,
resetColumns: () => true,
},
setup(props, { emit }) {
const { t } = useI18n('table')
const columns = computed(() => props.columns.filter(hasColumnKey))
const rootKeys = computed(
() => new Set(columns.value.map(({ key }) => key)),
)
const leaves = computed(() => getLeafColumns(props.columns))
const visibleCount = computed(
() => leaves.value.filter(({ key }) => !props.hiddenKeys.has(key)).length,
)
const reorder = ({ node, dragNode, dropPosition }: TreeDropInfo) => {
if (
dropPosition === 'inside' ||
node.key === dragNode.key ||
node.key == null
)
return
const dragged = columns.value.find(({ key }) => key === dragNode.key)
const remaining = columns.value.filter(({ key }) => key !== dragNode.key)
const targetIndex = remaining.findIndex(({ key }) => key === node.key)
if (!dragged || targetIndex < 0) return
remaining.splice(
targetIndex + (dropPosition === 'after' ? 1 : 0),
0,
dragged,
)
emit(
'reorderColumns',
remaining.map(({ key }) => key),
)
}
const arrangeTools = (column: KeyedColumn) => {
const hasWidth =
'children' in column
? column.children.every((child) => typeof child.width === 'number')
: typeof column.width === 'number'
return (
<NFlex align="center" size={4}>
<ToolButton
icon="directional/row_head"
label={t(
hasWidth || column.fixed === 'left'
? 'pinStart'
: 'pinNeedsWidth',
)}
disabled={!hasWidth && column.fixed !== 'left'}
aria-pressed={column.fixed === 'left'}
onClick={() =>
emit('patchColumn', column.key, {
fixed: column.fixed === 'left' ? void 0 : 'left',
})
}
/>
{!('children' in column) ? (
<ToolButton
icon="directional/resize_h"
label={t('resize')}
aria-pressed={!!column.resizable}
onClick={() =>
emit('patchColumn', column.key, {
resizable: !column.resizable,
})
}
/>
) : null}
<ToolButton
icon="directional/row_end"
label={t(
hasWidth || column.fixed === 'right' ? 'pinEnd' : 'pinNeedsWidth',
)}
disabled={!hasWidth && column.fixed !== 'right'}
aria-pressed={column.fixed === 'right'}
onClick={() =>
emit('patchColumn', column.key, {
fixed: column.fixed === 'right' ? void 0 : 'right',
})
}
/>
</NFlex>
)
}
const toTree = (items: KeyedColumn[], root: boolean): TreeOption[] =>
items.map((column) => ({
key: column.key,
label:
typeof column.title === 'string' ? column.title : String(column.key),
children:
'children' in column ? toTree(column.children, false) : void 0,
suffix: root ? () => arrangeTools(column) : void 0,
}))
const tree = computed(() => toTree(columns.value, true))
return () =>
columns.value.length ? (
<NPopover trigger="click" showArrow={false} placement="bottom-end">
{{
trigger: () => (
<ToolButton icon="action/setting" label={t('columns')} />
),
default: () => (
<fieldset class="r-table-columns">
<legend>{t('visibleColumns')}</legend>
<NTree
data={tree.value}
blockLine
defaultExpandAll
draggable
selectable={false}
allowDrop={({ node, dropPosition }) =>
node.key != null &&
rootKeys.value.has(node.key) &&
dropPosition !== 'inside'
}
onDrop={reorder}
renderLabel={({ option }) => {
const { key, label, children } = option
if (children || key == null) return label
const checked = !props.hiddenKeys.has(key)
return (
<label
class="r-table-columns__check"
onClick={(event) => event.stopPropagation()}
>
<input
type="checkbox"
checked={checked}
disabled={checked && visibleCount.value <= 1}
onKeydown={(event) => event.stopPropagation()}
onChange={(event) =>
emit(
'toggleColumn',
key,
(event.target as HTMLInputElement).checked,
)
}
/>
<span>{label}</span>
</label>
)
}}
/>
<NButton
size="small"
quaternary
disabled={!props.hiddenKeys.size}
onClick={() => emit('resetColumns')}
>
{t('showAllColumns')}
</NButton>
</fieldset>
),
}}
</NPopover>
) : null
},
})

View File

@ -0,0 +1,25 @@
import { useI18n } from '@/hooks/template/useI18n'
import { useFullscreen } from 'vue-hooks-plus'
import { config } from '../shared'
import ToolButton from './ToolButton'
export default defineComponent({
name: 'TableFullscreen',
setup() {
const wrapper = inject(config.wrapperKey)
const [isFullscreen, { toggleFullscreen, isEnabled }] =
useFullscreen(wrapper)
const { t } = useI18n('headerTooltip')
return () => (
<ToolButton
icon={
isFullscreen.value ? 'action/fullscreen_fold' : 'action/fullscreen'
}
label={t(isFullscreen.value ? 'CancelFullScreen' : 'FullScreen')}
disabled={!isEnabled}
onClick={toggleFullscreen}
/>
)
},
})

View File

@ -0,0 +1,28 @@
import { useI18n } from '@/hooks/template/useI18n'
import { NPopselect } from 'naive-ui'
import type { PropsComponentPopselectKeys } from '../types'
import ToolButton from './ToolButton'
export default defineComponent({
name: 'TablePropsSelect',
props: { striped: Boolean, bordered: Boolean },
emits: { change: (_value: PropsComponentPopselectKeys[]) => true },
setup(props, { emit }) {
const { t } = useI18n('table')
const keys = ['striped', 'bordered'] as const
return () => (
<NPopselect
value={keys.filter((key) => props[key])}
options={keys.map((key) => ({ label: t(key), value: key }))}
trigger="click"
multiple
onUpdateValue={(value) =>
emit('change', value as PropsComponentPopselectKeys[])
}
>
<ToolButton icon="action/more" label={t('appearance')} />
</NPopselect>
)
},
})

View File

@ -0,0 +1,87 @@
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NInput, NSelect } from 'naive-ui'
import { useId } from 'vue'
import type { PropType } from 'vue'
import type { TableProSearchField, TableSearchValues } from '../types'
export default defineComponent({
name: 'TableProSearch',
props: {
fields: { type: Array as PropType<TableProSearchField[]>, required: true },
},
emits: { search: (_values: TableSearchValues) => true },
setup(props, { emit }) {
const { t } = useI18n('table')
const id = useId()
const values = reactive<Record<string, string | number | null>>({})
const submit = (event: SubmitEvent) => {
event.preventDefault()
const result: TableSearchValues = {}
for (const { key } of props.fields) {
const value = values[key]
const normalized = typeof value === 'string' ? value.trim() : value
if (normalized != null && normalized !== '') result[key] = normalized
}
emit('search', result)
}
const reset = () => {
Object.keys(values).forEach((key) => delete values[key])
emit('search', {})
}
return () => (
<form class="r-table-search" onSubmit={submit}>
{props.fields.map(({ key, label, placeholder, options }, index) => {
const fieldId = `${id}-${index}`
return (
<div class="r-table-search__field" key={key}>
<label
for={options ? void 0 : fieldId}
id={options ? fieldId : void 0}
>
{label}
</label>
{options ? (
<NSelect
clearable
aria-labelledby={fieldId}
value={values[key] ?? null}
options={options}
placeholder={placeholder}
onUpdateValue={(value) => {
values[key] = value
}}
/>
) : (
<NInput
clearable
inputProps={{ id: fieldId }}
value={String(values[key] ?? '')}
placeholder={placeholder}
onUpdateValue={(value) => {
values[key] = value
}}
/>
)}
</div>
)
})}
<div class="r-table-search__actions">
<NButton onClick={reset}>{t('reset')}</NButton>
<NButton
attrType="submit"
type="primary"
class="r-table-search__submit"
>
{t('search')}
</NButton>
</div>
</form>
)
},
})

View File

@ -0,0 +1,32 @@
import { useI18n } from '@/hooks/template/useI18n'
import { NPopselect } from 'naive-ui'
import type { DataTableProps } from 'naive-ui'
import tableProps from '../props'
import ToolButton from './ToolButton'
export default defineComponent({
name: 'TableSizeSelect',
props: { size: tableProps.size },
emits: { change: (_size: DataTableProps['size']) => true },
setup(props, { emit }) {
const { t } = useI18n('table')
return () => (
<NPopselect
value={props.size ?? 'medium'}
options={[
{ label: t('compact'), value: 'small' },
{ label: t('standard'), value: 'medium' },
{ label: t('comfortable'), value: 'large' },
]}
trigger="click"
onUpdateValue={(value) => {
if (value === 'small' || value === 'medium' || value === 'large')
emit('change', value)
}}
>
<ToolButton icon="action/adjustment" label={t('density')} />
</NPopselect>
)
},
})

View File

@ -0,0 +1,34 @@
import { RIcon } from '@/components/base/RIcon'
import type { IconName } from '@/icons'
import { NButton } from 'naive-ui'
import type { PropType } from 'vue'
import { config } from '../shared'
export default defineComponent({
props: {
icon: { type: String as PropType<IconName>, required: true },
label: { type: String, required: true },
disabled: Boolean,
onClick: {
type: Function as PropType<(event: MouseEvent) => unknown>,
default: void 0,
},
},
setup(props) {
return () => (
<NButton
quaternary
size="small"
class="r-table__tool"
aria-label={props.label}
{...{ title: props.label }}
disabled={props.disabled}
onClick={props.onClick}
>
{{
icon: () => <RIcon name={props.icon} size={config.tableIconSize} />,
}}
</NButton>
)
},
})

View File

@ -0,0 +1,63 @@
import { get } from 'lodash-es'
import type { DataTableColumn, DataTableProps } from 'naive-ui'
import { getLeafColumns } from './columns'
const encodeCell = (value: unknown) => {
const text = value == null ? '' : String(value)
const formula =
typeof value !== 'number' &&
typeof value !== 'bigint' &&
/^[\s\uFEFF]*[=+\-@=+-@]|^[\t\r\n]/u.test(text)
return `"${formula ? "'" : ''}${text.replaceAll('"', '""')}"`
}
export const buildTableCsv = (
columns: DataTableColumn[],
data: Record<string, unknown>[],
getCell?: DataTableProps['getCsvCell'],
getHeader?: DataTableProps['getCsvHeader'],
) => {
const leaves = getLeafColumns(columns).filter(
(column) => column.allowExport !== false,
)
const header = leaves
.map((column) =>
encodeCell(
getHeader?.(column) ??
(typeof column.title === 'string' ? column.title : column.key),
),
)
.join(',')
return [
header,
...data.map((row) =>
leaves
.map((column) => {
const value = get(row, column.key)
return encodeCell(getCell ? getCell(value, row, column) : value)
})
.join(','),
),
].join('\r\n')
}
export const downloadTableCsv = (csv: string, fileName = 'data.csv') => {
const url = URL.createObjectURL(
new Blob(['\uFEFF', csv], { type: 'text/csv;charset=utf-8' }),
)
const link = document.createElement('a')
link.href = url
link.download = fileName.endsWith('.csv') ? fileName : `${fileName}.csv`
document.body.append(link)
try {
link.click()
} finally {
link.remove()
setTimeout(() => URL.revokeObjectURL(url), 0)
}
}

View File

@ -0,0 +1,165 @@
.r-table {
container: table-panel / inline-size;
display: flex;
flex-direction: column;
gap: 16px;
inline-size: 100%;
min-inline-size: 0;
&__result {
display: flex;
flex-direction: column;
gap: 8px;
min-inline-size: 0;
}
&__header {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px 16px;
h2 {
color: var(--r-text);
font-size: 18px;
font-weight: 650;
line-height: 1.4;
}
}
&__toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 6px;
margin-inline-start: auto;
}
&__heading {
min-inline-size: 0;
}
&--fill {
block-size: var(
--r-table-height,
max(
20rem,
calc(
var(--layout-content-height, 100dvh) - 2 *
var(--layout-content-gutter, 16px)
)
)
);
> .r-table__result,
> .r-table__result > .n-data-table {
flex: 1;
min-block-size: 0;
}
}
&:fullscreen {
box-sizing: border-box;
padding: 12px;
background: var(--r-surface);
overflow: auto;
}
&__footer,
&__action {
color: var(--r-text-secondary);
font-size: 13px;
}
&__tool[aria-pressed='true'] {
color: var(--r-selected-text);
background: var(--r-surface-hover);
}
}
.r-table-search {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 12px;
&__field {
display: grid;
flex: 0 1 16rem;
min-inline-size: min(100%, 12rem);
gap: 6px;
color: var(--r-text-secondary);
font-size: 13px;
font-weight: 550;
}
&__actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
}
.r-template--dark .r-table-search__submit.n-button {
&,
&:hover,
&:focus-visible,
&:active {
color: var(--r-text);
background-color: var(--r-surface-hover);
}
}
@container table-panel (inline-size < 600px) {
.r-table__toolbar {
gap: 4px;
}
.r-table__tool {
inline-size: 30px;
padding-inline: 0;
}
.r-table-search__field {
flex: 1 1 100%;
}
.r-table-search__actions {
margin-inline-start: auto;
}
}
.r-table-columns {
min-inline-size: 0;
max-inline-size: min(26rem, calc(100vw - 36px));
max-block-size: min(28rem, 65dvh);
overflow: auto;
padding: 0;
border: 0;
legend {
margin-block-end: 6px;
color: var(--r-text);
font-weight: 600;
}
&__check {
display: inline-flex;
align-items: center;
min-block-size: 44px;
gap: 8px;
cursor: pointer;
input {
inline-size: 16px;
block-size: 16px;
flex: none;
accent-color: var(--r-theme-primary-color);
}
span {
overflow-wrap: anywhere;
}
}
}

View File

@ -0,0 +1,187 @@
import { unrefElement } from '@/utils/vue/unref-element'
import { get } from 'lodash-es'
import type { DataTableColumn } from 'naive-ui'
import { getLeafColumns, hasColumnKey } from './columns'
import type { TableProPrintOptions } from './types'
const printStyles = `
@page { margin: 12mm; }
:root { color-scheme: light; }
body { margin: 0; background: white; color: #171717; font: 9pt/1.4 system-ui, sans-serif; }
table { width: 100%; border-collapse: collapse; }
thead { display: table-header-group; }
tr { break-inside: avoid; }
th, td { padding: 3pt 5pt; border: 1px solid #b7bec6; text-align: start; overflow-wrap: anywhere; vertical-align: top; }
th { font-weight: 650; background: #f1f3f5; word-break: keep-all; overflow-wrap: break-word; }
img, svg { max-width: 100%; }
[data-print-ignore] { display: none !important; }
`
const displayText = (value: unknown): string => {
if (value == null) return ''
if (Array.isArray(value)) return value.map(displayText).join(', ')
if (value instanceof Date) return value.toLocaleString()
return ['string', 'number', 'boolean', 'bigint'].includes(typeof value)
? String(value)
: ''
}
export const buildPrintableTable = (
doc: Document,
columns: DataTableColumn[],
rows: Record<string, unknown>[],
{ formatHeader, formatCell }: TableProPrintOptions = {},
) => {
const table = doc.createElement('table')
const leaves = getLeafColumns(columns)
const header = table.createTHead()
const depth = (items: DataTableColumn[]): number =>
Math.max(
0,
...items
.filter(hasColumnKey)
.map((column) =>
'children' in column
? getLeafColumns(column.children).length
? 1 + depth(column.children)
: 0
: 1,
),
)
const headers = Array.from({ length: depth(columns) }, () =>
header.insertRow(),
)
const appendHeaders = (items: DataTableColumn[], level: number) => {
for (const column of items.filter(hasColumnKey)) {
const children =
'children' in column ? getLeafColumns(column.children) : null
if (children && !children.length) continue
const cell = doc.createElement('th')
cell.textContent =
(children
? void 0
: formatHeader?.(column as (typeof leaves)[number])) ??
(typeof column.title === 'string' ? column.title : String(column.key))
if ('children' in column) {
cell.colSpan = children!.length
cell.scope = 'colgroup'
appendHeaders(column.children, level + 1)
} else {
cell.rowSpan = headers.length - level
cell.scope = 'col'
}
headers[level].append(cell)
}
}
appendHeaders(columns, 0)
const body = table.createTBody()
for (const row of rows) {
const tr = body.insertRow()
for (const column of leaves) {
const value = get(row, column.key)
tr.insertCell().textContent =
formatCell?.(value, row, column) ?? displayText(value)
}
}
return table
}
const cloneRegion = (target: HTMLElement) => {
const clone = target.cloneNode(true) as HTMLElement
clone
.querySelectorAll('script, iframe, object, embed, link, base, meta')
.forEach((node) => node.remove())
for (const node of [clone, ...clone.querySelectorAll('*')]) {
for (const name of node.getAttributeNames()) {
if (name.startsWith('on')) node.removeAttribute(name)
}
}
return clone
}
export const resolvePrintContent = (
options: TableProPrintOptions,
defaultTable: () => HTMLElement | null,
) => {
if (options.target == null) return defaultTable()
const target = unrefElement(options.target)
return target instanceof HTMLElement ? cloneRegion(target) : null
}
export const printTableContent = async (
content: HTMLElement,
options: TableProPrintOptions,
) => {
const frame = document.createElement('iframe')
frame.tabIndex = -1
frame.setAttribute('sandbox', 'allow-same-origin allow-modals')
frame.setAttribute('aria-hidden', 'true')
frame.title = options.title || 'TablePro print'
frame.style.cssText = 'position:fixed;inset:0;width:0;height:0;border:0;'
document.body.append(frame)
let cleanupTimer: ReturnType<typeof setTimeout> | undefined
const cleanup = () => {
clearTimeout(cleanupTimer)
frame.remove()
}
try {
const doc = frame.contentDocument
const view = frame.contentWindow
if (!doc || !view) throw new Error('Print document is unavailable.')
doc.documentElement.lang = document.documentElement.lang
doc.title = options.title ?? ''
const style = doc.createElement('style')
style.textContent = printStyles + (options.style ?? '')
doc.head.append(style)
doc.body.append(content)
const images = [...doc.images]
if (images.length) {
let imageTimer: ReturnType<typeof setTimeout> | undefined
await Promise.race([
Promise.allSettled(images.map((img) => img.decode())),
new Promise<void>((resolve) => {
imageTimer = setTimeout(resolve, 1500)
}),
]).finally(() => clearTimeout(imageTimer))
}
view.addEventListener('afterprint', cleanup, { once: true })
// 浏览器未派发 afterprint 时,兜底释放打印文档。
cleanupTimer = setTimeout(cleanup, 120_000)
view.focus()
view.print()
return true
} catch (error) {
cleanup()
throw error
}
}

View File

@ -0,0 +1,26 @@
import { dataTableProps } from 'naive-ui'
import type { DataTableColumn, DataTableInst, DropdownOption } from 'naive-ui'
import type { PropType, VNode } from 'vue'
import type { TableProPrintOptions } from './types'
const props = {
...dataTableProps,
bare: Boolean,
autoHeight: Boolean,
tool: { type: Boolean, default: true },
title: [String, Object] as PropType<string | VNode>,
downloadCsvTableOptions: Object as PropType<
Parameters<DataTableInst['downloadCsv']>[0]
>,
printTableOptions: Object as PropType<TableProPrintOptions>,
columnStateKey: String,
contextMenuOptions: Array as PropType<DropdownOption[]>,
onContextMenuClick: Function as PropType<
(key: string | number, option: DropdownOption) => void
>,
'onUpdate:columns': Function as PropType<
(columns: DataTableColumn[]) => void
>,
} as const
export default props

View File

@ -0,0 +1,8 @@
import type { InjectionKey, ShallowRef } from 'vue'
export const config = {
tableIconSize: '18',
wrapperKey: Symbol('table-pro-wrapper') as InjectionKey<
Readonly<ShallowRef<HTMLElement | null>>
>,
}

View File

@ -0,0 +1,46 @@
import type { BasicTarget } from '@/types'
import type { DataTableInst, DataTableProps, SelectOption } from 'naive-ui'
import type { LeafColumn } from './columns'
export interface TableProPrintOptions {
target?: BasicTarget<HTMLElement>
title?: string
style?: string
formatHeader?: (column: LeafColumn) => string
formatCell?: (
value: unknown,
row: Record<string, unknown>,
column: LeafColumn,
) => string
}
export interface TablePanelInst {
getTableInstance: () => DataTableInst | null
print: (options?: TableProPrintOptions) => Promise<boolean>
downloadCsv: DataTableInst['downloadCsv']
}
export interface TableProParams extends Record<string, unknown> {
page?: number
pageSize?: number
}
export interface TableProResult {
data: NonNullable<DataTableProps['data']>
total: number
}
export type TableProRequest = (
params: TableProParams,
signal: AbortSignal,
) => Promise<TableProResult>
export type TableProSearchField = {
key: string
label: string
placeholder?: string
options?: SelectOption[]
}
export type TableSearchValues = Record<string, string | number>
export type PropsComponentPopselectKeys = 'striped' | 'bordered'

View File

@ -8,12 +8,11 @@ export * from './base/RIcon'
export * from './base/RIframe'
export * from './base/RModal'
export * from './base/RMoreDropdown'
export * from './base/RTable'
export * from './base/RTablePro'
export * from './base/RTransitionComponent'
export * from './base/RForm'
export * from './base/RSegment'
export * from './base/RBarcode'
export * from '../components/pro/RTablePro'
export * from './base/RFlow'
export { RCollapse, RDraggableCard }
@ -21,7 +20,6 @@ export { RCollapse, RDraggableCard }
export type * from './base/RChart/src/types'
export type * from './base/RCollapseGrid/src/types'
export type * from './base/RIframe/src/types'
export type * from './base/RTable/src/types'
export type * from './base/RTransitionComponent/src/types'
export type * from './base/RForm/src/types'
export type * from './base/RModal/src/types'

View File

@ -1,24 +0,0 @@
import type { ExtractPropTypes } from 'vue'
import { useTablePro } from './src/hooks/useTablePro'
import tableProProps from './src/props'
import RTablePro from './src/TablePro'
import type {
BasePagination,
FormatRangeTime,
TablePagination,
TableProFieldNames,
TableRequestConfig,
} from './src/types'
type TableProProps = ExtractPropTypes<typeof tableProProps>
export type {
TableProProps,
BasePagination,
TablePagination,
FormatRangeTime,
TableRequestConfig,
TableProFieldNames,
}
export { RTablePro, useTablePro, tableProProps }

View File

@ -1,188 +0,0 @@
import { usePagination } from '@/hooks'
import type { Recordable } from '@/types'
import { call, removeDuplicateKeys } from '@/utils'
import { omit } from 'lodash-es'
import { NFlex } from 'naive-ui'
import type { RTableInst } from '../../..'
import { RTable } from '../../../base/RTable'
import useTable from '../../../base/RTable/src/hooks/useTable'
import props from './props'
import type { TablePagination, TableProInst, TableRequestConfig } from './types'
export default defineComponent({
name: 'RTablePro',
props,
setup(props, ctx) {
const { expose } = ctx
const [register, tableFns] = useTable()
const [
paginationRef,
{
getPage,
getPageSize,
setCallback,
setItemCount,
resetPagination,
getItemCount,
setPage,
setPageSize,
},
] = usePagination(void 0, {
prefix: props.paginationPrefix,
})
// 获取最新 pagination 值 - 使用 computed 避免函数重新创建
const tablePagination = computed<TablePagination>(() => ({
page: getPage(),
pageSize: getPageSize(),
itemCount: getItemCount(),
}))
// 派发表格更新事件
const emitTableUpdate = () => {
const { onTablePaginationUpdate } = props
if (onTablePaginationUpdate) {
call(onTablePaginationUpdate, tablePagination.value)
}
}
// 合并请求参数
const combineRequestParams = <T extends Recordable>(
extraConfig?: TableRequestConfig<T>,
) => {
const config = Object.assign({}, props.requestConfig, extraConfig)
const {
formatRangeTime,
excludeParams,
autoDeleteDuplicateKeys = true,
} = config
let params: Recordable = config.params || {}
// 转换时间范围,该功能仅支持 NDatePicker range 模式参数
if (formatRangeTime?.length && params) {
formatRangeTime.forEach(({ key, target }) => {
const val = params[key] as [number, number] | null
if (val && target?.length === 2) {
params[target[0]] = val[0]
params[target[1]] = val[1]
}
// 清空时间参数的 key
delete params[key]
})
}
if (autoDeleteDuplicateKeys) {
params = removeDuplicateKeys(params)
}
// 排除指定的请求参数
if (excludeParams) {
params = omit(params, excludeParams)
}
const requestParams = Object.assign({}, params, {
page: getPage(),
pageSize: getPageSize(),
})
return requestParams as T & { page: number; pageSize: number }
}
// 同步执行 request 请求,允许重置 pagination 请求
const runResetPaginationRequest: TableProInst['runTableRequest'] = (
extraConfig,
reset = true,
) => {
if (reset) {
resetPagination()
}
const requestParams = combineRequestParams(extraConfig)
props.request?.(requestParams)
}
// 异步执行 request 请求,允许重置 pagination 请求,返回 Promise 对象
const runResetPaginationRequestAsync: TableProInst['runAsyncTableRequest'] =
async (extraConfig, reset = true) => {
if (reset) {
resetPagination()
}
const requestParams = combineRequestParams(extraConfig)
await props.request?.(requestParams)
}
watchEffect(() => {
setItemCount(props.paginationCount)
setCallback(() => {
const { manual } = props
if (!manual) {
runResetPaginationRequest(void 0, false)
}
emitTableUpdate()
})
})
onMounted(() => {
const { onRegister } = props
if (onRegister) {
call(onRegister, {
...(tableFns as unknown as RTableInst),
getTablePagination: () => tablePagination.value,
runTableRequest: runResetPaginationRequest,
runAsyncTableRequest: runResetPaginationRequestAsync,
getCurrentTableRequestParams: combineRequestParams,
resetTablePagination: resetPagination,
setPage,
setPageSize,
getPage,
getPageSize,
})
}
})
expose()
return {
register,
paginationRef,
}
},
render() {
const { register, $props, paginationRef, $slots } = this
const {
onRegister,
showPagination,
takeoverAutoHeight,
flexAutoHeight,
...rest
} = $props
const { collapse, ...restSlots } = $slots
const baseProps = {
onRegister: register,
pagination: showPagination ? paginationRef : void 0,
flexAutoHeight: takeoverAutoHeight || flexAutoHeight,
...rest,
}
if (takeoverAutoHeight) {
return (
<NFlex vertical class="h-full">
{collapse?.()}
<RTable {...baseProps}>{restSlots}</RTable>
</NFlex>
)
}
return <RTable {...baseProps}>{restSlots}</RTable>
},
})

View File

@ -1,271 +0,0 @@
import type {
ColumnKey,
CsvOptionsType,
FilterState,
ScrollToOptions,
SortOrder,
} from '@/components/base/RTable/src/types'
import type { Recordable } from '@/types'
import type { PrintDomOptions } from '@/utils'
import type { TableProInst, TableRequestConfig } from '../types'
/**
*
* @description
* 获取 TablePro 实例上的一些方法。
* 使用方法与 useTable 类似。
*/
export const useTablePro = () => {
const tableInst = ref<TableProInst>()
const register = (inst: TableProInst) => {
if (inst) {
tableInst.value = inst
}
}
/**
*
* @description
* 获取 TablePro 实例。
*/
const getTableProInstance = () => {
if (!tableInst.value) {
throw new Error(
'[useTablePro]: table instance is not ready yet. if you are using useTablePro, please make sure you have called register method in onRegister event.',
)
}
return tableInst.value
}
/**
*
* @description
* 获取 statistics, pagination 更新信息。
*/
const getTablePagination = () =>
getTableProInstance().getTablePagination.call(null)
/**
*
* @param extraConfig 额外请求合并配置项
* @param reset 是否重置分页请求
*
* @description
* 手动触发表格请求,用于手动刷新表格。
* 如果设置了 manual 为 true,则需要手动调用该函数。
* 该函数会自动匹配 statistics, pagination 更新的值去请求。
*
* 允许手动配置 TableRequestConfig 参数,会自动合并 props tableRequestConfig 配置。
* 并且,运行该函数会重置 pagination 为初始状态。
*/
const runTableRequest = <
T extends Recordable,
ExcludeParams extends keyof T = keyof T,
>(
extraConfig?: TableRequestConfig<T, ExcludeParams>,
reset?: boolean,
) => getTableProInstance().runTableRequest.call(null, extraConfig, reset)
/**
*
* @description
* 清空所有 filter 状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter
*/
const clearFilters = () => getTableProInstance().clearFilters.call(null)
/**
*
* @description
* 清空所有 sort 状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter
*/
const clearSorter = () => getTableProInstance().clearSorter.call(null)
/**
*
* @param options 下载 CSV 配置项
*
* @description
* 下载 CSV。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#export-csv.vue
*/
const downloadCsv = (options?: CsvOptionsType) =>
getTableProInstance().downloadCsv.call(null, options)
/**
*
* @param filters 过滤器状态配置
*
* @description
* 设定表格当前的过滤器。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter
*/
const filters = (filters: FilterState | null) =>
getTableProInstance().filters.call(null, filters)
/**
*
* @param page 页数
*
* @description
* 手动设置 page。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const page = (page: number) => getTableProInstance().page.call(null, page)
/**
*
* @param options 滚动配置项
*
* @description
* 滚动内容。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const scrollTo: ScrollToOptions = (options) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getTableProInstance().scrollTo(options as any)
/**
*
* @param columnKey 列键
* @param order 排序顺序
*
* @description
* 设定表格的过滤状态。
*
* @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods
*/
const sort = (columnKey: ColumnKey, order: SortOrder) =>
getTableProInstance().sort.call(null, columnKey, order)
/**
*
* @param options 打印选项
*
* @description
* 打印表格。
*/
const print = (options?: PrintDomOptions) =>
getTableProInstance().print.call(null, options)
/**
*
* @param extraConfig 额外请求合并配置项
* @param excludeParams 排除的请求参数
*
* @description
* 获取当前内部表格请求参数。
*/
const getCurrentTableRequestParams = <
T extends Recordable,
ExcludeParams extends keyof T = keyof T,
>(
extraConfig?: TableRequestConfig<T, ExcludeParams>,
): T & Recordable =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
getTableProInstance().getCurrentTableRequestParams.call(null, extraConfig)
/**
*
* @param extraConfig 额外请求合并配置项
*
* @description
* 重置表格分页。
*/
const resetTablePagination = () =>
getTableProInstance().resetTablePagination.call(null)
/**
*
* @param extraConfig 额外请求合并配置项
* @param reset 是否重置分页请求
*
* @description
* 异步手动触发表格请求,用于手动刷新表格。
*/
const runAsyncTableRequest = <
T extends Recordable,
ExcludeParams extends keyof T = keyof T,
>(
extraConfig?: TableRequestConfig<T, ExcludeParams>,
reset?: boolean,
) => getTableProInstance().runAsyncTableRequest.call(null, extraConfig, reset)
/**
*
* @description
* 获取 TablePro 组件配置。
*/
const getTableProConfig = () => getTableProInstance().config
/**
*
* @description
* 获取表格分页页码。
*/
const getPage = () => getTableProInstance().getPage.call(null)
/**
*
* @description
/**
*
* @description
* 获取表格分页每页条数。
*/
const getPageSize = () => getTableProInstance().getPageSize.call(null)
/**
*
* @description
* 设置表格分页页码。
*/
const setPage = (page: number) =>
getTableProInstance().setPage.call(null, page)
/**
*
* @description
* 设置表格分页每页条数。
*/
const setPageSize = (pageSize: number) =>
getTableProInstance().setPageSize.call(null, pageSize)
return [
register,
{
clearFilters,
getTableProInstance,
clearSorter,
downloadCsv,
filters,
page,
scrollTo,
sort,
getTablePagination,
runTableRequest,
print,
getCurrentTableRequestParams,
resetTablePagination,
runAsyncTableRequest,
getTableProConfig,
getPage,
getPageSize,
setPage,
setPageSize,
},
] as const
}
export type UseTableProReturn = ReturnType<typeof useTablePro>

View File

@ -1,136 +0,0 @@
import { tableProps } from '@/components'
import type { AnyFn } from '@/types'
import { omit } from 'lodash-es'
import type { PropType } from 'vue'
import type {
PaginationPrefix,
TablePaginationUpdate,
TableProInst,
TableRequestConfig,
} from './types'
const props = {
...omit(tableProps, ['pagination']),
/**
*
* @description
* 分页总数。
*
* @default 1
*/
paginationCount: {
type: Number,
default: 1,
},
/**
*
* @description
* 注册 useTablePro 钩子函数。
*
* @default undefined
*/
onRegister: {
type: Function as PropType<(inst: TableProInst) => void>,
default: void 0,
},
/**
*
* @description
* 是否需要手动控制表格的刷新。
* 如果设置为 true,在 Pagination 更新时,不会自动触发表格的刷新。
*
* @default false
*/
manual: {
type: Boolean,
default: false,
},
/**
*
* @description
* 刷新表格的请求函数。
* 该属性用于配置表格的刷新请求函数。
*
* 如果设置了该属性,则会在表格刷新时调用该函数。
*
* @default undefined
*/
request: {
type: Function as PropType<AnyFn>,
},
/**
*
* @description
* pagination 更新时的回调函数。
*
* @default undefined
*/
onTablePaginationUpdate: {
type: Function as PropType<TablePaginationUpdate>,
},
/**
*
* @description
* 请求函数的参数。
* 该属性用于配置请求函数的参数。
*
* @default undefined
*/
requestConfig: {
type: Object as PropType<TableRequestConfig>,
},
/**
*
* @description
* 是否显示分页器。
* 如果需要显示分页器,则设置为 true。
*
* @default false
*/
showPagination: {
type: Boolean,
default: false,
},
/**
*
* @description
* 设置表格数据为异步状态。
* 当你使用该组件的时候,会默认认为你总是异步获取数据,所以重写了原组件的 remote,
* 现在 remote 默认为开启状态,也就是默认为 true。
*
* @default true
*/
remote: {
type: Boolean,
default: true,
},
/**
*
* @description
* 分页器前缀。
* 自定义配置分页器前缀。
*
* @default (info) => `共 ${info.itemCount} 条`
*/
paginationPrefix: {
type: Function as PropType<PaginationPrefix>,
default: (info: Parameters<NonNullable<PaginationPrefix>>[0]) =>
`共 ${info.itemCount} 条`,
},
/**
*
* @description
* 是否接管表格的渲染。
* 如果你觉得配置 flexAutoHeight 属性过于麻烦,可以设置为 true,然后就能直接使用 flexAutoHeight,无需做过多的配置。
*
* 并且,一旦启用该属性,flexAutoHeight 属性将强制启用。
*
* @default false
*/
takeoverAutoHeight: {
type: Boolean,
default: false,
},
}
export default props

View File

@ -1,247 +0,0 @@
import type { RTableInst, TableProps } from '@/components'
import type { UsePaginationOptions } from '@/hooks'
import type { Recordable } from '@/types'
export type FormatRangeTime = {
/**
*
* @description
* 请求参数中需要格式化的时间参数字段。
*/
key: string | number
/**
*
* @description
* 后端接口中需要的起止时间参数字段。
*/
target: [string | number, string | number]
}
export interface BasePagination {
page: number
pageSize: number
itemCount: number
}
/**
*
* @description
* Pagination 分页配置。
*/
export type TablePagination = BasePagination
export type TablePaginationUpdate = (
pagination: Readonly<TablePagination>,
) => void
export type PaginationPrefix = UsePaginationOptions['prefix']
export interface TableRequestConfig<
Params = Recordable,
ExcludeParams extends keyof Params = keyof Params,
> {
/**
*
* @description
* 请求参数。
* @default undefined
*/
params?: Params
/**
*
* @description
* 格式化时间范围,该字段用于格式化时间范围。
* 并且仅支持 NDatePicker range 模式。
* 如果在请求的参数中,有时间段的字段,且需要格式化时间段,则需要配置该字段。
*
* @default undefined
*/
formatRangeTime?: FormatRangeTime[]
/**
*
* @description
* 排除的请求参数,该字段用于排除请求参数。
*
* @default undefined
*/
excludeParams?: ExcludeParams[]
/**
*
* @description
* 是否自动移除重复的请求参数。
*
* @default true
*/
autoDeleteDuplicateKeys?: boolean
}
export type TableProProps = Omit<TableProps, 'pagination'>
export interface TableProInst extends Omit<RTableInst, 'getTableInstance'> {
/**
*
* @description
* 获取 pagination 更新值。
*
* @example
* const [register, { getTablePagination }] = useTablePro()
*
* // 获取当前 pagination 的值
* const pagination = getTablePagination()
*/
getTablePagination: () => TablePagination
/**
*
* @param extraConfig 额外请求合并配置项
* @param reset 是否重置分页请求
*
* @description
* 手动触发表格请求,用于手动刷新表格。
*
* @example
* const [register, { runTableRequest }] = useTablePro()
*
* // 重置分页请求
* runTableRequest(void 0, true)
* runTableRequest()
* // 不重置分页请求
* runTableRequest(void 0, false)
*/
runTableRequest: <
T extends Recordable,
ExcludeParams extends keyof T = keyof T,
>(
extraConfig?: TableRequestConfig<T, ExcludeParams>,
reset?: boolean,
) => void
/**
*
* @param extraConfig 额外请求合并配置项
* @param reset 是否重置分页请求
*
* @description
* 异步手动触发表格请求,用于手动刷新表格。
*
* @example
* const [register, { runAsyncTableRequest }] = useTablePro()
*
* // 重置分页请求
* runAsyncTableRequest(void 0, true)
* runAsyncTableRequest()
* // 不重置分页请求
* runAsyncTableRequest(void 0, false)
*/
runAsyncTableRequest: <
T extends Recordable,
ExcludeParams extends keyof T = keyof T,
>(
extraConfig?: TableRequestConfig<T, ExcludeParams>,
reset?: boolean,
) => Promise<void>
/**
*
* @param extraConfig 额外请求合并配置项
*
* @description
* 获取当前内部表格请求参数。
*
* @example
* const [register, { getCurrentTableRequestParams }] = useTablePro()
*
* // 获取当前内部表格请求参数
* const params = getCurrentTableRequestParams()
*/
getCurrentTableRequestParams: <
T extends Recordable,
ExcludeParams extends keyof T = keyof T,
>(
extraConfig?: TableRequestConfig<T, ExcludeParams>,
) => TableRequestConfig<T, ExcludeParams>['params'] & Recordable
/**
*
* @description
* 重置表格分页。
*
* @example
* const [register, { resetTablePagination }] = useTablePro()
*
* // 重置表格分页为初始化状态,即第 1 页,每页 10 条数据
* resetTablePagination()
*/
resetTablePagination: () => void
/**
*
* @description
* 设置表格分页页码。
*
* @example
* const [register, { setPage }] = useTablePro()
*
* // 设置表格分页页码为 2
* setPage(2)
*/
setPage: (page: number) => void
/**
*
* @description
* 设置表格分页每页条数。
*
* @example
* const [register, { setPageSize }] = useTablePro()
*
* // 设置表格分页每页条数为 20
* setPageSize(20)
*/
setPageSize: (pageSize: number) => void
/**
*
* @description
* 获取表格分页页码。
*
* @example
* const [register, { getPage }] = useTablePro()
*
* // 获取表格分页页码
* const page = getPage()
*/
getPage: () => number
/**
*
* @description
* 获取表格分页每页条数。
*
* @example
* const [register, { getPageSize }] = useTablePro()
*
* // 获取表格分页每页条数
* const pageSize = getPageSize()
*/
getPageSize: () => number
}
export interface TableProFieldNames {
/**
*
* @description
* 分页器页码字段。
*
* @default 'page'
*/
page: string
/**
*
* @description
* 分页器每页条数字段。
*
* @default 'pageSize'
*/
pageSize: string
/**
*
* @description
* 分页器总条数字段。
*
* @default 'itemCount'
*/
itemCount: string
}

66
src/demo-data/people.ts Normal file
View File

@ -0,0 +1,66 @@
import type { PaginationResponse } from '@/types/modules/axios'
import { faker } from '@faker-js/faker/locale/zh_CN'
export interface Person {
id: string
name: string
age: number
address: string
createDate: string
email: string
}
export interface PersonListParams {
page?: number
pageSize?: number
email?: string
name?: string
sortAge?: 'ascend' | 'descend'
}
let people: Person[] | undefined
export const listPeople = ({
page,
pageSize,
email,
name,
sortAge,
}: PersonListParams = {}): PaginationResponse<Person[]> => {
// 同一会话内复用数据,让翻页和从上一页复制的搜索词都可重复使用。
people ??= Array.from({ length: 100 }, () => ({
id: faker.string.uuid(),
address: faker.location.state() + faker.location.city(),
email: faker.internet.email(),
name: faker.person.fullName(),
age: faker.number.int({ min: 18, max: 60 }),
createDate: faker.date.past().toISOString().slice(0, 10),
}))
const emailQuery = email?.trim().toLowerCase()
const nameQuery = name?.trim().toLowerCase()
const matches = people.filter(
(person) =>
(!emailQuery || person.email.toLowerCase().includes(emailQuery)) &&
(!nameQuery || person.name.toLowerCase().includes(nameQuery)),
)
if (sortAge) {
const direction = sortAge === 'ascend' ? 1 : -1
matches.sort((left, right) => direction * (left.age - right.age))
}
const validPage = page !== void 0 && Number.isSafeInteger(page) && page > 0
const validSize =
pageSize !== void 0 && Number.isSafeInteger(pageSize) && pageSize > 0
const start = validPage && validSize ? (page - 1) * pageSize : 0
return {
code: 200,
msg: '请求成功',
data:
validPage && validSize ? matches.slice(start, start + pageSize) : matches,
total: matches.length,
}
}

View File

@ -550,7 +550,8 @@ export default defineComponent({
<NButton
quaternary
class="override-button__menu-tag"
focusable={false}
aria-label={$t('layout.maximize')}
{...{ title: $t('layout.maximize') }}
onClick={maximizeBtnClick}
>
{{

View File

@ -109,6 +109,7 @@ export default defineComponent({
return {
t,
isFullscreen,
leftIconOptions,
rightTooltipIconOptions,
toolIconClick,
@ -172,16 +173,17 @@ export default defineComponent({
class="override-button__layout"
quaternary
size="medium"
key={curr.name}
key={curr.eventKey ?? curr.name}
aria-label={this.t<string>(
curr.eventKey === 'setting'
? 'headerTooltip.Setting'
: curr.eventKey === 'github'
? 'headerTooltip.Github'
: 'headerTooltip.FullScreen',
: this.isFullscreen
? 'headerTooltip.CancelFullScreen'
: 'headerTooltip.FullScreen',
)}
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)}
focusable={false}
>
<RIcon name={curr.name} size={16} cursor="pointer" />
</NButton>

View File

@ -101,11 +101,11 @@ export const createLeftIconOptions = (opts: IconOptionsFC) => {
* - false: 不展示搜索按钮
*/
export const createRightIconOptions = (opts: IconOptionsFC) => {
const { isTabletOrSmaller } = opts
const { isTabletOrSmaller, isFullscreen } = opts
const basicOptions: IconOptions[] = [
{
name: 'action/fullscreen',
name: isFullscreen.value ? 'action/fullscreen_fold' : 'action/fullscreen',
size: 18,
eventKey: 'fullscreen',
},

View File

@ -17,10 +17,3 @@
display: none;
}
}
.layout-content__maximize-out {
position: fixed;
top: 12px;
right: 20px;
z-index: 1000;
}

View File

@ -2,10 +2,10 @@ import { useRuntimeGetters } from '@/store'
import './index.scss'
import AppRequestCancelerProvider from '@/app-components/provider/AppRequestCancelerProvider'
import { LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE } from '@/app-config'
import { RIcon, RTransitionComponent } from '@/components'
import { useI18n, useMaximize } from '@/hooks'
import { RTransitionComponent } from '@/components'
import { useI18n } from '@/hooks'
import { useSettingGetters } from '@/store'
import { NButton, NSpin } from 'naive-ui'
import { NSpin } from 'naive-ui'
import type { GlobalThemeOverrides } from 'naive-ui'
export default defineComponent({
@ -14,17 +14,12 @@ export default defineComponent({
const router = useRouter()
const { t } = useI18n()
const { maximize } = useMaximize()
const { getContentTransition } = useSettingGetters()
const spinning = ref(false)
const themeOverridesSpin: GlobalThemeOverrides['Spin'] = {
opacitySpinning: '0',
}
const {
globalMainLayoutLoad,
layoutContentMaximize,
layoutContentSpinning,
} = useRuntimeGetters()
const { globalMainLayoutLoad, layoutContentSpinning } = useRuntimeGetters()
const setupLayoutContentSpin = () => {
const removeBefore = router.beforeEach(() => {
@ -53,17 +48,13 @@ export default defineComponent({
spinning,
themeOverridesSpin,
getContentTransition,
layoutContentMaximize,
maximize,
layoutContentSpinning,
}
},
render() {
const {
globalMainLayoutLoad,
layoutContentMaximize,
layoutContentSpinning,
maximize,
spinning,
themeOverridesSpin,
getContentTransition,
@ -76,24 +67,8 @@ export default defineComponent({
description={this.t('layout.loading')}
size="large"
themeOverrides={themeOverridesSpin}
class={[
'layout-content-spin',
layoutContentMaximize
? 'r-layout-full__viewer-content--maximize'
: null,
]}
class="layout-content-spin"
>
{layoutContentMaximize ? (
<NButton
class="layout-content__maximize-out"
aria-label={this.t('layout.restore')}
onClick={() => {
maximize(false)
}}
>
<RIcon name="action/out" size="16" cursor="pointer" />
</NButton>
) : null}
<AppRequestCancelerProvider />
{globalMainLayoutLoad ? (
<RTransitionComponent

View File

@ -37,26 +37,71 @@
}
.r-layout-content-inner {
--layout-content-gutter: var(--layout-content-padding);
box-sizing: border-box;
container-type: inline-size;
width: 100%;
max-width: var(--layout-content-max-width);
margin-inline: auto;
padding: var(--layout-content-padding);
padding: var(--layout-content-gutter);
flex: 1;
min-width: 0;
}
}
.r-layout-content--maximized {
--layout-restore-height: 49px;
--layout-content-height: calc(100dvh - var(--layout-restore-height));
position: fixed !important;
inset: 0;
width: 100dvw !important;
height: 100dvh !important;
.r-layout-header-region,
.r-layout-tabs-region,
.r-layout-footer-region {
display: none;
}
}
.r-layout-content-restore {
position: sticky;
inset-block-start: 0;
z-index: 3;
display: flex;
justify-content: flex-end;
flex: none;
padding: 8px max(12px, var(--layout-content-padding));
border-block-end: 1px solid var(--r-line);
background: var(--r-surface);
&__button {
display: inline-flex;
align-items: center;
gap: 8px;
min-block-size: 32px;
padding-inline: 10px;
border: 1px solid var(--r-control-border);
border-radius: 8px;
color: var(--r-text);
background: var(--r-surface-muted);
font-size: 13px;
font-weight: 550;
cursor: pointer;
&:hover {
background: var(--r-surface-hover);
}
}
}
@media (max-width: 768px) {
.r-layout-full .r-layout-content-inner {
padding: min(var(--layout-content-padding), 16px);
--layout-content-gutter: min(
var(--layout-content-padding),
clamp(10px, 4vw, 16px)
);
}
}

View File

@ -2,7 +2,8 @@ import './index.scss'
import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar'
import UnlockScreen from '@/app-components/app/AppLockScreen/components/UnlockScreen'
import { LAYOUT_CONTENT_REF } from '@/app-config'
import { useDevice, useMaximize } from '@/hooks'
import { RIcon } from '@/components/base/RIcon'
import { useDevice, useI18n, useMaximize } from '@/hooks'
import { layoutCssVars } from '@/layout/layout-css-vars'
import {
useMenuGetters,
@ -12,6 +13,7 @@ import {
} from '@/store'
import { useEventListener } from '@vueuse/core'
import { NLayout, NLayoutContent } from 'naive-ui'
import type { VNode } from 'vue'
import Menu from './components/Menu'
import TopNavigation from './components/TopNavigation'
import {
@ -35,6 +37,8 @@ export default defineComponent({
useRuntimeGetters()
const { setRuntimeState } = useRuntimeActions()
const { maximize } = useMaximize()
const { t } = useI18n('layout')
let previouslyFocused: HTMLElement | null = null
const { isTabletOrSmaller } = useDevice()
const { getLockAppScreen } = useAppLockScreen()
const cssVars = layoutCssVars([headerRef, tagsRef, footerRef])
@ -50,12 +54,41 @@ export default defineComponent({
)
useEventListener(window, 'keydown', (event) => {
if (event.key === 'Escape' && layoutContentMaximize.value) maximize(false)
if (
event.key === 'Escape' &&
!event.defaultPrevented &&
layoutContentMaximize.value
)
maximize(false)
})
watch(
layoutContentMaximize,
(active) => {
if (!active) return
const focused = document.activeElement
previouslyFocused = focused instanceof HTMLElement ? focused : null
},
{ flush: 'sync' },
)
watch(
layoutContentMaximize,
(active) => {
if (!active && previouslyFocused?.isConnected) {
previouslyFocused.focus({ preventScroll: true })
}
},
{ flush: 'post' },
)
onBeforeUnmount(() => setRuntimeState('layoutContentMaximize', false))
const header = () => (
<div ref={headerRef} class="r-layout-header-region">
<div
ref={headerRef}
class="r-layout-header-region"
inert={layoutContentMaximize.value}
>
{slots.header ? (
slots.header()
) : (
@ -68,13 +101,21 @@ export default defineComponent({
)
const tabs = () =>
getMenuTagSwitch.value ? (
<div ref={tagsRef} class="r-layout-tabs-region">
<div
ref={tagsRef}
class="r-layout-tabs-region"
inert={layoutContentMaximize.value}
>
{slots.tabs?.() ?? <FeatureWrapper />}
</div>
) : null
const footer = () =>
getCopyrightSwitch.value ? (
<div ref={footerRef} class="r-layout-footer-region">
<div
ref={footerRef}
class="r-layout-footer-region"
inert={layoutContentMaximize.value}
>
{slots.footer?.() ?? <FooterWrapper />}
</div>
) : null
@ -134,6 +175,26 @@ export default defineComponent({
nativeScrollbar={false}
contentClass="r-layout-content-scroll"
>
{layoutContentMaximize.value ? (
<div class="r-layout-content-restore">
<button
type="button"
class="r-layout-content-restore__button"
aria-label={t('restore')}
title={t('restore')}
{...{
onVnodeMounted: ({ el }: VNode) => {
if (el instanceof HTMLElement)
el.focus({ preventScroll: true })
},
}}
onClick={() => maximize(false)}
>
<RIcon name="action/out" size={16} />
{t('restoreButton')}
</button>
</div>
) : null}
{!config.fixedHeader ? (
<>
{header()}

View File

@ -21,7 +21,9 @@
"extension": "Extend the layout",
"slots": "Use header, sidebar, tabs, footer and default content slots. Update the Pinia configuration to switch layouts.",
"navigation": "Main navigation",
"maximize": "Maximize content",
"restore": "Restore content size (Esc)",
"restoreButton": "Exit fullscreen",
"loading": "Loading",
"tab": "Layout",
"toggleMenu": "Open navigation menu",

View File

@ -27,11 +27,16 @@
"RouterDemo": "Same Level Router Demo",
"Segment": "Segment",
"SvgIcon": "SVG Icon",
"Table": "Table",
"TableAutoHeight": "Table Auto Height",
"Table": "Tables",
"TableAutoHeight": "Auto height",
"TablePro": "Table Pro",
"TemplateHooks": "Template Hooks",
"scrollReveal": "Scroll Reveal",
"LayoutDemo": "Layout playground",
"WebHooks": "Web Hooks"
"WebHooks": "Web Hooks",
"TableBasic": "Basic table",
"TableRemote": "Remote search and pagination",
"TableColumns": "Column preferences",
"TablePrinting": "Printing and custom regions",
"TableCustom": "Slots and instance methods"
}

View File

@ -0,0 +1,51 @@
{
"httpSource": "Local mock API",
"localSource": "Local demo data",
"directory": "People directory",
"name": "Name",
"email": "Email",
"address": "Region",
"age": "Age",
"created": "Created",
"nameHint": "Enter part of a name",
"emailHint": "Enter part of an email address",
"reset": "Reset",
"search": "Search",
"reload": "Refresh",
"csv": "Export CSV",
"print": "Print table",
"total": "{count} records",
"clearSelection": "Clear selection ({count})",
"requestError": "Couldn't load the data",
"retry": "Retry",
"density": "Table density",
"compact": "Compact",
"standard": "Standard",
"comfortable": "Comfortable",
"appearance": "Table appearance",
"striped": "Striped rows",
"bordered": "Table border",
"columns": "Column settings",
"pinStart": "Pin to start",
"pinEnd": "Pin to end",
"resize": "Allow resizing",
"showFooter": "Show footer slot",
"showAction": "Show action slot",
"footerExample": "Use this area for totals or notes.",
"actionExample": "Use this area for bulk actions.",
"visibleColumns": "Visible columns",
"showAllColumns": "Show all columns",
"printError": "Could not open print preview",
"demoFailure": "Simulate request failure",
"virtualRows": "Virtual rows",
"contactGroup": "Contact details",
"includeIdField": "Include the ID field",
"printDemoTitle": "Print the current page",
"printSummary": "Print a separate summary",
"printSummaryText": "A summary for the directory. This printout excludes the table, toolbar and pagination.",
"contextAction": "Row context menu action",
"firstPage": "Go to first page",
"twentyRows": "20 per page",
"customFooter": "Right-click a row to open the example context menu.",
"pinNeedsWidth": "Set a numeric column width before pinning"
}

View File

@ -21,7 +21,9 @@
"extension": "扩展布局",
"slots": "布局提供 header、sidebar、tabs、footer 和默认内容插槽。通过 Pinia 更新配置即可切换布局。",
"navigation": "主导航",
"maximize": "最大化内容区域",
"restore": "退出内容最大化(Esc)",
"restoreButton": "退出全屏",
"loading": "正在加载",
"tab": "布局",
"toggleMenu": "打开导航菜单",

View File

@ -28,10 +28,15 @@
"Segment": "分段器",
"SvgIcon": "SVG 图标",
"Table": "表格",
"TableAutoHeight": "自适应高度表格",
"TableAutoHeight": "自适应高度",
"TablePro": "高级表格",
"TemplateHooks": "模板 Hooks",
"scrollReveal": "滚动动画",
"LayoutDemo": "布局实验室",
"WebHooks": "Web Hooks"
"WebHooks": "Web Hooks",
"TableBasic": "纯表格",
"TableRemote": "远端查询与分页",
"TableColumns": "列设置与缓存",
"TablePrinting": "打印与自定义区域",
"TableCustom": "插槽与实例操作"
}

View File

@ -0,0 +1,51 @@
{
"httpSource": "本地 Mock 接口",
"localSource": "本地示例数据",
"directory": "人员列表",
"name": "姓名",
"email": "邮箱",
"address": "地区",
"age": "年龄",
"created": "创建日期",
"nameHint": "输入姓名关键词",
"emailHint": "输入邮箱关键词",
"reset": "重置",
"search": "查询",
"reload": "刷新",
"csv": "导出 CSV",
"print": "打印表格",
"total": "共 {count} 条",
"clearSelection": "清除已选({count})",
"requestError": "数据加载失败",
"retry": "重试",
"density": "表格密度",
"compact": "紧凑",
"standard": "标准",
"comfortable": "宽松",
"appearance": "表格外观",
"striped": "斑马条纹",
"bordered": "表格边框",
"columns": "列设置",
"pinStart": "固定在列首",
"pinEnd": "固定在列尾",
"resize": "允许调整列宽",
"showFooter": "显示底部插槽",
"showAction": "显示操作插槽",
"footerExample": "这里可以放置统计或补充说明。",
"actionExample": "这里可以放置批量操作。",
"visibleColumns": "显示列",
"showAllColumns": "恢复全部列",
"printError": "无法打开打印预览",
"demoFailure": "模拟请求失败",
"virtualRows": "虚拟滚动",
"contactGroup": "联系方式",
"includeIdField": "启用 ID 字段",
"printDemoTitle": "打印当前页",
"printSummary": "打印独立摘要",
"printSummaryText": "当前页人员目录。打印此摘要不包含表格、工具栏或分页。",
"contextAction": "触发行右键菜单操作",
"firstPage": "回到第 1 页",
"twentyRows": "每页 20 条",
"customFooter": "示例:右键表格行可打开自定义菜单。",
"pinNeedsWidth": "固定列需要数字列宽"
}

View File

@ -1,19 +0,0 @@
import { t } from '@/hooks/web/useI18n'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const mockDemo: AppRouteRecordRaw = {
path: '/mock-demo',
component: () => import('@/views/demo/mock-demo/index'),
meta: {
i18nKey: t('menu.Mock'),
icon: 'navigation/other',
order: 3,
keepAlive: false,
extra: {
label: 'usePagination',
},
},
}
export default mockDemo

View File

@ -1,19 +0,0 @@
import { t } from '@/hooks/web/useI18n'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const axios: AppRouteRecordRaw = {
path: '/table-auto-height',
name: 'RTableAutoHeight',
component: () => import('@/views/demo/table-auto-height'),
meta: {
i18nKey: t('menu.TableAutoHeight'),
icon: 'navigation/other',
order: 3,
extra: {
label: 'new',
},
},
}
export default axios

View File

@ -1,18 +0,0 @@
import { t } from '@/hooks/web/useI18n'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const r: AppRouteRecordRaw = {
path: '/table-pro',
component: () => import('@/views/demo/table-pro-demo'),
meta: {
i18nKey: t('menu.TablePro'),
icon: 'navigation/other',
order: 2,
extra: {
label: 'TablePro',
},
},
}
export default r

View File

@ -1,18 +0,0 @@
import { t } from '@/hooks/web/useI18n'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const table: AppRouteRecordRaw = {
path: '/table',
component: () => import('@/views/demo/table/index'),
meta: {
i18nKey: t('menu.Table'),
icon: 'navigation/other',
order: 2,
extra: {
label: 'useTable',
},
},
}
export default table

View File

@ -0,0 +1,51 @@
import { t } from '@/hooks/web/useI18n'
import type { AppRouteRecordRaw } from '@/router/types'
const tables: AppRouteRecordRaw = {
path: '/tables',
meta: {
i18nKey: t('menu.Table'),
icon: 'navigation/table',
order: 2,
},
children: [
{
path: 'basic',
name: 'TableDemoBasic',
component: () => import('@/views/demo/tables/basic'),
meta: { i18nKey: t('menu.TableBasic') },
},
{
path: 'remote',
name: 'TableDemoRemote',
component: () => import('@/views/demo/tables/remote'),
meta: { i18nKey: t('menu.TableRemote') },
},
{
path: 'auto-height',
name: 'TableDemoAutoHeight',
component: () => import('@/views/demo/tables/auto-height'),
meta: { i18nKey: t('menu.TableAutoHeight') },
},
{
path: 'columns',
name: 'TableDemoColumns',
component: () => import('@/views/demo/tables/columns'),
meta: { i18nKey: t('menu.TableColumns') },
},
{
path: 'printing',
name: 'TableDemoPrinting',
component: () => import('@/views/demo/tables/printing'),
meta: { i18nKey: t('menu.TablePrinting') },
},
{
path: 'custom',
name: 'TableDemoCustom',
component: () => import('@/views/demo/tables/custom'),
meta: { i18nKey: t('menu.TableCustom') },
},
],
}
export default tables

View File

@ -24,6 +24,11 @@ export default [
component: Layout,
children: [
...appExpandRoutes(),
{ path: '/tables', redirect: '/tables/basic' },
{ path: '/table', redirect: '/tables/basic' },
{ path: '/table-pro', redirect: '/tables/remote' },
{ path: '/mock-demo', redirect: '/tables/remote' },
{ path: '/table-auto-height', redirect: '/tables/auto-height' },
/**
*
* @description

View File

@ -1,168 +0,0 @@
import { getPersonList } from '@/api/demo/mock/person'
import type { Person } from '@/api/demo/mock/person'
import { useHookPlusRequest } from '@/axios'
import { RCollapse, RTable, useCheckedRowKeys } from '@/components'
import { usePagination } from '@/hooks'
import { NButton, NCard, NFlex, NForm, NFormItemGi, NInput } from 'naive-ui'
const MockDemo = defineComponent({
name: 'MockDemo',
setup() {
const columns = [
{
type: 'selection',
multiple: true,
},
{
title: 'id',
key: 'id',
},
{
title: '邮箱',
key: 'email',
},
{
title: '地址',
key: 'address',
},
{
title: '姓名',
key: 'name',
},
{
title: '年龄',
key: 'age',
},
{
title: '创建时间',
key: 'createDate',
},
{
title: '操作',
key: 'action',
render: (row: Person) => {
return (
<NFlex align="center">
<NButton
type="primary"
text
onClick={() => {
window.$message.info('查看')
}}
>
查看
</NButton>
<NButton
type="primary"
text
onClick={() => {
window.$message.warning('编辑')
}}
>
编辑
</NButton>
<NButton
type="error"
text
onClick={() => {
window.$message.error('删除')
}}
>
删除
</NButton>
</NFlex>
)
},
},
]
const condition = reactive({
email: null,
})
const [
paginationRef,
{ getPage, getPageSize, setItemCount, getCallback, setPage, setPageSize },
] = usePagination(() => {
personFetchRun({
page: getPage(),
pageSize: getPageSize(),
email: condition.email,
})
})
const {
data: personData,
loading: personLoading,
run: personFetchRun,
} = useHookPlusRequest(getPersonList, {
defaultParams: [
{
page: getPage(),
pageSize: getPageSize(),
email: condition.email,
},
],
onSuccess: (res) => {
const { total } = res
setItemCount(total)
},
})
return {
personData,
personLoading,
columns,
...toRefs(condition),
getCallback,
paginationRef,
}
},
render() {
return (
<NFlex vertical>
<NCard title="Mock 数据">
<h2>
mock
数据使用。但是,并没有启用生产环境的部署,所以生产环境结果为空。
</h2>
</NCard>
<NCard title="提示">
<h2>
RTable
组件有一个比较值得注意的地方就是,该组件会自动的按照数据量计算分页条数。所以你在异步获取数据的时候,一定要手动设置
remote 属性为 true,并且设置 itemCount 或者 pageCount。
</h2>
</NCard>
<NForm labelPlacement="left">
<RCollapse cols={3}>
{{
default: () => (
<>
<NFormItemGi label="邮箱">
<NInput v-model:value={this.email} clearable />
</NFormItemGi>
</>
),
action: () => (
<NButton type="primary" onClick={this.getCallback?.bind(this)}>
搜索
</NButton>
),
}}
</RCollapse>
</NForm>
<RTable
title="Mock数据表格"
data={this.personData?.data}
loading={this.personLoading}
v-model:columns={this.columns}
pagination={this.paginationRef}
remote
rowKey={(row) => row.id}
/>
</NFlex>
)
},
})
export default MockDemo

View File

@ -1,4 +1,4 @@
import { RTable } from '@/components'
import { RTablePro } from '@/components'
import { NButton, NFlex } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
@ -72,7 +72,7 @@ const RouterDemoHome = defineComponent({
render() {
return (
<NFlex>
<RTable v-model:columns={this.columns} data={this.dataSource} />
<RTablePro bare columns={this.columns} data={this.dataSource} />
</NFlex>
)
},

View File

@ -1,216 +0,0 @@
import { RCollapse, RTablePro } from '@/components'
import { useDayjs } from '@/hooks'
import { uuid } from '@/utils'
import { faker } from '@faker-js/faker/locale/zh_CN'
import dayjs from 'dayjs'
import {
NButton,
NDatePicker,
NFlex,
NFormItemGi,
NInput,
NSelect,
NSwitch,
NTag,
} from 'naive-ui'
type RowData = {
key: number | string
name: string
age: number
address: string
tags: string[]
remark: string
status: string
statusText: string
signTimeEnd: number
signTimeStart: number
}
export default defineComponent({
name: 'TableAutoHeight',
setup() {
const { format } = useDayjs()
const baseColumns = ref<GlobalDataTableColumns<RowData>>([
{
type: 'selection',
},
{
title: 'Name',
key: 'name',
},
{
title: 'Sign Status',
key: 'statusText',
},
{
title: 'Sign Time',
key: 'signTimeStart',
render: (row: RowData) =>
format(row.signTimeStart) + ' ~ ' + format(row.signTimeEnd),
},
{
title: 'Age',
key: 'age',
},
{
title: 'Address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
render: (row: RowData) => {
const tags = row.tags.map((tagKey) => {
return (
<NTag type="info" bordered={false} style="margin-right: 6px">
{tagKey}
</NTag>
)
})
return tags
},
},
{
title: 'Remark',
key: 'remark',
},
])
const mockPersonList = ref<RowData[]>(
(() => {
const length = 30
const list: RowData[] = []
const time = dayjs().valueOf()
for (let i = 0; i < length; i++) {
list.push({
key: uuid(),
name: faker.person.fullName(),
age: i + 20,
address: faker.location.city(),
tags: ['nice', 'developer'],
remark: '我是一条很长很长的备注',
status: i % 2 === 0 ? 'success' : 'error',
statusText: i % 2 === 0 ? '在线' : '离线',
signTimeStart: dayjs(time)
.add(i * 2, 'year')
.valueOf(),
signTimeEnd: dayjs(time)
.add(i + 5, 'day')
.valueOf(),
})
}
return list
})(),
)
const switchRef = ref({
footer: false,
action: false,
flexAutoHeight: true,
})
return {
mockPersonList,
baseColumns,
switchRef,
}
},
render() {
const { mockPersonList, switchRef } = this
return (
<RTablePro
takeoverAutoHeight
data={mockPersonList}
v-model:columns={this.baseColumns}
showPagination
paginationCount={mockPersonList.length}
remote={false}
title={
<NFlex>
<NFlex align="center">
<NButton text focusable={false}>
底部区域插槽
</NButton>
<NSwitch v-model:value={switchRef.footer} />
</NFlex>
<NFlex align="center">
<NButton text focusable={false}>
操作区域插槽
</NButton>
<NSwitch v-model:value={switchRef.action} />
</NFlex>
</NFlex>
}
>
{{
collapse: () => (
<RCollapse bordered open={false}>
{{
default: () => (
<>
<NFormItemGi label="用户名">
<NInput clearable />
</NFormItemGi>
<NFormItemGi label="状态">
<NSelect
clearable
options={[
{
label: '成功',
value: 'success',
},
{
label: '失败',
value: 'error',
},
]}
/>
</NFormItemGi>
<NFormItemGi label="登陆时间">
<NDatePicker type="datetimerange" clearable />
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput clearable />
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput clearable />
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput clearable />
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput clearable />
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput clearable />
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput clearable />
</NFormItemGi>
</>
),
action: () => (
<NFlex>
<NButton type="primary">查询</NButton>
</NFlex>
),
}}
</RCollapse>
),
tableFooter: () =>
switchRef.footer
? '表格的底部内容区域插槽,有时候你可能会用上'
: null,
tableAction: () =>
switchRef.action
? '表格的操作区域内容插槽,有时候可能会用上'
: null,
}}
</RTablePro>
)
},
})

View File

@ -1,532 +0,0 @@
import { useHookPlusRequest } from '@/axios'
import {
RCollapse,
RIcon,
RTablePro,
useCheckedRowKeys,
useForm,
useTablePro,
} from '@/components'
import { useDayjs } from '@/hooks'
import { uuid } from '@/utils'
import { faker } from '@faker-js/faker/locale/zh_CN'
import dayjs from 'dayjs'
import {
NButton,
NCard,
NDatePicker,
NFlex,
NFormItem,
NFormItemGi,
NInput,
NRadioButton,
NRadioGroup,
NSelect,
NTag,
NText,
useDialog,
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
type RowData = {
key: number | string
name: string | null
age: number
address: string
tags: string[]
remark: string
status: string | null
statusText: string
signTimeEnd: number
signTimeStart: number
}
interface ParamsRef extends Partial<
Pick<RowData, 'name' | 'status' | 'signTimeStart' | 'signTimeEnd'>
> {
page?: number
pageSize?: number
RangeTime?: [number, number] | null
}
interface BasicResponse<T = unknown> {
/**
*
* @description
* 返回数据。
*/
data: T
/**
*
* @description
* 返回描述信息。
*/
message: string
/**
*
* @description
* 返回状态码。
*/
code: number
/**
*
* @description
* 额外的错误描述信息。
*/
exceptionMessage: string
}
interface PaginationResponse<T = unknown> extends BasicResponse<T> {
/**
*
* @description
* 分页总条数。
*/
total: number
/**
*
* @description
* 分页页数。
*/
pageSize: number
/**
*
* @description
* 当前页数。
*/
page: number
}
export default defineComponent({
name: 'TableProDemo',
setup() {
const { format } = useDayjs()
const { info: infoDialog } = useDialog()
const [register, { formModel, reset }] = useForm<ParamsRef>({
RangeTime: null,
name: null,
status: null,
})
/**
*
* @description
* register: 注册表格实例
* runTableRequest: 获取 TablePro 内部管理的请求方法,会自动合并 page, pageSize 等参数,如果有。
* getUpdateInfo: 如果需要自定义请求情况,可以使用该方法获取最新的 page, pageSize 等参数。
*/
const [
tableProRegister,
{
runTableRequest,
getCurrentTableRequestParams,
print,
downloadCsv,
runAsyncTableRequest,
setPage,
setPageSize,
resetTablePagination,
},
] = useTablePro()
// 表格数据
const tableDataRef = ref<RowData[]>([])
// 表格列
const baseColumns = ref<DataTableColumns<RowData>>([
{
type: 'selection',
},
{
title: 'Name',
key: 'name',
},
{
title: 'Sign Status',
key: 'statusText',
},
{
title: 'Sign Time',
key: 'signTimeStart',
render: (row: RowData) =>
format(row.signTimeStart) + ' ~ ' + format(row.signTimeEnd),
},
{
title: 'Age',
key: 'age',
},
{
title: 'Address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
render: (row: RowData) => {
const tags = row.tags.map((tagKey) => {
return (
<NTag type="info" bordered={false} style="margin-right: 6px">
{tagKey}
</NTag>
)
})
return tags
},
},
{
title: 'Remark',
key: 'remark',
},
])
// 表格分页数据
const itemCountRef = ref(0)
// 查询条件
const conditionRef = ref<ParamsRef>(formModel())
// 缓存模拟数据,不用关心
const mockPersonList = ref<RowData[]>(
(() => {
const length = 30
const list: RowData[] = []
const time = dayjs().valueOf()
for (let i = 0; i < length; i++) {
list.push({
key: uuid(),
name: faker.person.fullName(),
age: i + 20,
address: faker.location.city(),
tags: ['nice', 'developer'],
remark: '我是一条很长很长的备注',
status: i % 2 === 0 ? 'success' : 'error',
statusText: i % 2 === 0 ? '在线' : '离线',
signTimeStart: dayjs(time)
.add(i * 2, 'year')
.valueOf(),
signTimeEnd: dayjs(time)
.add(i + 5, 'day')
.valueOf(),
})
}
return list
})(),
)
const radioRef = ref({
pagination: true,
manual: false,
})
const [
checkedRowKeys,
{ checkedRowKeysBind, getKeys, getRows, clearKey, clearAll, selectKey },
] = useCheckedRowKeys(tableDataRef, baseColumns, {
rowKey: 'key',
onChange: (keys, rows, meta) => {},
})
const collapseRef = ref(true)
const isNullOrUndefined = (value: unknown) => {
return value === null || value === void 0
}
// 模拟请求
const getPersonList = (
params: ParamsRef,
): Promise<PaginationResponse<RowData[]>> => {
return new Promise((resolve) => {
const {
page = 1,
pageSize = 10,
name,
status,
signTimeStart,
signTimeEnd,
} = params || {}
let list: RowData[] = mockPersonList.value
const defaultLength = mockPersonList.value.length
if (name) {
list = list.filter((curr) => curr.name!.includes(name))
}
if (status) {
list = list.filter((curr) => curr.status === status)
}
if (signTimeStart && signTimeEnd) {
list = list.filter((curr) => {
return (
curr.signTimeStart >= signTimeStart &&
curr.signTimeEnd <= signTimeEnd
)
})
}
list = list.slice((page - 1) * pageSize, page * pageSize)
setTimeout(() => {
resolve({
code: 0,
data: list,
total:
isNullOrUndefined(status) &&
isNullOrUndefined(name) &&
(isNullOrUndefined(signTimeStart) ||
isNullOrUndefined(signTimeEnd))
? defaultLength
: list.length,
message: 'success',
page,
pageSize,
} as PaginationResponse<RowData[]>)
}, 1000)
})
}
const { run: runGetPersonList, loading: loadingGetPersonList } =
useHookPlusRequest(getPersonList, {
onSuccess: (res) => {
const { data, total } = res
tableDataRef.value = data
itemCountRef.value = total
},
})
return {
tableDataRef,
baseColumns,
itemCountRef,
loadingGetPersonList,
runGetPersonList,
conditionRef,
radioRef,
runTableRequest,
tableProRegister,
print,
downloadCsv,
checkedRowKeysBind,
checkedRowKeys,
getKeys,
getRows,
clearKey,
clearAll,
collapseRef,
selectKey,
register,
reset,
setPage,
setPageSize,
resetTablePagination,
infoDialog,
}
},
render() {
const {
tableDataRef,
baseColumns,
itemCountRef,
loadingGetPersonList,
runGetPersonList,
conditionRef,
radioRef,
runTableRequest,
tableProRegister,
print,
downloadCsv,
checkedRowKeysBind,
getKeys,
getRows,
clearKey,
clearAll,
selectKey,
register,
reset,
setPage,
setPageSize,
resetTablePagination,
infoDialog,
} = this
return (
<NFlex vertical class="h-full">
<RCollapse open={this.collapseRef} onRegister={register}>
{{
default: () => (
<>
<NFormItemGi label="用户名">
<NInput v-model:value={conditionRef.name} clearable />
</NFormItemGi>
<NFormItemGi label="状态">
<NSelect
v-model:value={conditionRef.status}
clearable
options={[
{
label: '成功',
value: 'success',
},
{
label: '失败',
value: 'error',
},
]}
/>
</NFormItemGi>
<NFormItemGi label="登陆时间">
<NDatePicker
type="datetimerange"
v-model:value={conditionRef.RangeTime}
clearable
/>
</NFormItemGi>
<NFormItemGi label="演示折叠的条件框">
<NInput readonly placeholder="我只是为了占位" />
</NFormItemGi>
</>
),
action: () => (
<NFlex>
<NButton onClick={() => reset(this.conditionRef)}>重置</NButton>
<NButton
type="primary"
onClick={() => runTableRequest()}
loading={loadingGetPersonList}
>
查询
</NButton>
</NFlex>
),
collapse: (open: boolean) =>
open ? (
<NButton onClick={() => (this.collapseRef = true)} secondary>
{{
default: () => '受控展开',
icon: () => <RIcon name="system/dark" size="18" />,
}}
</NButton>
) : (
<NButton onClick={() => (this.collapseRef = false)} secondary>
{{
default: () => '受控收起',
icon: () => <RIcon name="system/light" size="18" />,
}}
</NButton>
),
}}
</RCollapse>
<NCard title="常用高级拓展功能">
<NFlex>
<NFormItem label="分页">
<NRadioGroup v-model:value={radioRef.pagination}>
<NRadioButton value={true}>显示分页</NRadioButton>
<NRadioButton value={false}>隐藏分页</NRadioButton>
</NRadioGroup>
</NFormItem>
<NFormItem label="自动更新">
<NRadioGroup v-model:value={radioRef.manual}>
<NRadioButton value={false}>自动更新</NRadioButton>
<NRadioButton value={true}>取消自动</NRadioButton>
</NRadioGroup>
</NFormItem>
</NFlex>
</NCard>
<NCard title="useTablePro 部分方法">
<NFlex>
<NButton type="primary" onClick={() => print()}>
打印
</NButton>
<NButton
type="primary"
onClick={() => {
infoDialog({
title: '下载 CSV',
content: '下载 CSV',
positiveText: '下载',
negativeText: '取消',
onPositiveClick: () => {
downloadCsv()
},
})
}}
>
下载 csv
</NButton>
<NButton type="primary" onClick={() => setPage(2)}>
设置分页页码为 2
</NButton>
<NButton type="primary" onClick={() => setPageSize(20)}>
设置分页每页条数为 20
</NButton>
<NButton type="primary" onClick={() => resetTablePagination()}>
重置分页
</NButton>
</NFlex>
</NCard>
<NCard title="useCheckedRowKeys 部分方法">
<NFlex>
<NButton
type="primary"
onClick={() => {
const key = tableDataRef[1].key
selectKey(key)
}}
>
选中第二行
</NButton>
<NButton
type="primary"
onClick={() => {
const key = tableDataRef[1].key
clearKey(key)
}}
>
取消选中第二行
</NButton>
<NButton
type="primary"
onClick={() => {
tableDataRef?.forEach((curr) => selectKey(curr.key))
}}
>
选中当前页面所有行
</NButton>
<NButton
type="primary"
onClick={() => {
clearAll()
}}
>
取消所有已选中行
</NButton>
</NFlex>
</NCard>
<RTablePro
takeoverAutoHeight
onRegister={tableProRegister}
data={tableDataRef}
v-model:columns={this.baseColumns}
loading={loadingGetPersonList}
// 如果需要设置分页功能,则该参数必传
paginationCount={itemCountRef}
request={runGetPersonList}
requestConfig={{
params: conditionRef,
// 这是后台的统计字段,根据实际情况配置
formatRangeTime: [
{
key: 'RangeTime',
target: ['signTimeStart', 'signTimeEnd'],
},
],
}}
showPagination={radioRef.pagination}
manual={radioRef.manual}
rowKey={(row) => row.key}
v-model:checkedRowKeys={this.checkedRowKeys}
onUpdateCheckedRowKeys={checkedRowKeysBind}
/>
</NFlex>
)
},
})

View File

@ -1,382 +0,0 @@
import {
RCollapse,
RIcon,
RMoreDropdown,
RTable,
useCheckedRowKeys,
useTable,
} from '@/components'
import { uuid } from '@/utils'
import {
NAlert,
NButton,
NCard,
NDatePicker,
NFlex,
NGridItem,
NInput,
NPopover,
NSelect,
NSwitch,
NTag,
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
type RowData = {
key: number | string
name: string
age: number
address: string
tags: string[]
remark: string
}
const TableView = defineComponent({
name: 'TableView',
setup() {
// 使用以下 hooks 的时候,应该注意调用时机
const [
register,
{
getTableInstance,
clearFilters,
clearSorter,
scrollTo,
filters,
sort,
downloadCsv,
print,
},
] = useTable()
const baseColumns: DataTableColumns<RowData> = [
{
type: 'selection',
},
{
title: 'Name',
key: 'name',
filterOptions: [
{
label: 'John Brown',
value: 'John Brown',
},
{
label: 'Jim Green',
value: 'Jim Green',
},
],
filter: (value, row) => row.name.includes(value.toString()),
},
{
title: 'Age',
key: 'age',
sorter: (a, b) => a.age - b.age,
},
{
title: 'Address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
render: (row: RowData) => {
const tags = row.tags.map((tagKey) => {
return (
<NTag type="info" bordered={false} style="margin-right: 6px">
{tagKey}
</NTag>
)
})
return tags
},
},
{
title: 'Remark',
key: 'remark',
},
{
title: 'Action',
key: 'actions',
render: (row: RowData) => (
<NFlex align="center">
<NButton size="tiny">查看</NButton>
<RMoreDropdown
options={[
{
label: '编辑',
key: 'edit',
},
{
label: '新增',
key: 'add',
},
]}
onSelect={(key) => {
window.$message.info(`当前选择: ${key}`)
}}
/>
</NFlex>
),
},
]
const actionColumns = ref<DataTableColumns<RowData>>(
[...baseColumns].map((curr, idx) => ({
...curr,
})),
)
const tableData = ref<RowData[]>([])
const tableMenuOptions = [
{
label: '编辑',
key: 'edit',
},
{
label: () => <span style="color: red;">删除</span>,
key: 'delete',
},
]
const state = reactive({
gridItemCount: 4,
gridCollapsedRows: 1,
tableLoading: false,
})
const [
checkedRowKeys,
{ checkedRowKeysBind, getKeys, getRows, clearKey, clearAll, selectKey },
] = useCheckedRowKeys(tableData, actionColumns, {
rowKey: 'key',
onChange: (keys, rows, meta) => {},
})
const createTableData = () => {
for (let i = 0; i < 10; i++) {
tableData.value.push({
key: uuid(),
name: i % 2 === 0 ? 'John Brown' : 'Jim Green',
age: i + 20,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
remark: '我是一条很长很长的备注',
})
}
}
const menuSelect = (key: string | number) => {
window.$message.info(`${key}`)
}
const clearSecondIndexRow = () => {
const { key } = tableData.value[1]
clearKey(key)
}
const selectAll = () => {
const keys = tableData.value.map((curr) => curr.key)
keys.forEach((curr) => selectKey(curr))
}
const selectSecondIndexRow = () => {
const { key } = tableData.value[1]
selectKey(key)
}
createTableData()
return {
...toRefs(state),
tableData,
actionColumns,
baseColumns,
tableMenuOptions,
menuSelect,
register,
getKeys,
getRows,
clearKey,
clearAll,
checkedRowKeysBind,
checkedRowKeys,
clearSecondIndexRow,
selectAll,
selectSecondIndexRow,
clearFilters,
clearSorter,
scrollTo,
filters,
sort,
downloadCsv,
getTableInstance,
print,
}
},
render() {
const {
register,
clearAll,
checkedRowKeysBind,
clearSecondIndexRow,
selectAll,
selectSecondIndexRow,
clearFilters,
clearSorter,
scrollTo,
filters,
sort,
downloadCsv,
getTableInstance,
getRows,
getKeys,
print,
} = this
return (
<NFlex vertical>
<NCard title="RTable">
基于 NDataTable 封装,继承该组件所有 props 属性。查看 RTable props
文件即可查看该组件拓展项
</NCard>
<NCard title="useTable">
<NFlex vertical style="width: 100%">
<NAlert title="DataTable Methods" type="info">
其余的方法查看{' '}
<a
style="color: transparent"
href="https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods"
>
Naive UI
</a>
官网,保持一致。
</NAlert>
<NFlex>
<NButton onClick={clearSorter.bind(this)}>清除所有排序</NButton>
<NButton onClick={clearFilters.bind(this)}>清除所有过滤</NButton>
<NButton
onClick={() => {
downloadCsv()
}}
>
下载 CSV
</NButton>
<NButton onClick={() => getTableInstance()}>
getTableInstance
</NButton>
<NButton onClick={() => print()}>打印</NButton>
</NFlex>
</NFlex>
</NCard>
<NCard title="useCheckedRowKeys">
<NFlex vertical>
<NFlex>
<NButton onClick={selectAll.bind(this)}>选中所有行</NButton>
<NButton onClick={clearAll.bind(this)}>取消所有已选中行</NButton>
<NButton onClick={selectSecondIndexRow.bind(this)}>
选中第二行
</NButton>
<NButton onClick={clearSecondIndexRow.bind(this)}>
取消第二行选中
</NButton>
</NFlex>
<NFlex>
{this.checkedRowKeys.map((curr) => (
<NTag type="success" key={curr}>
{curr}
</NTag>
))}
</NFlex>
</NFlex>
</NCard>
<RCollapse
collapsedRows={this.gridCollapsedRows}
cols={this.gridItemCount}
onUpdateOpen={(value: boolean) =>
window.$message.info(
`我是 RCollapse 组件${value ? '收起' : '展开'}的回调函数`,
)
}
>
{{
action: () => (
<>
<NButton type="primary">搜索</NButton>
<NButton>重置</NButton>
</>
),
default: () => (
<>
<NGridItem>
<NSelect />
</NGridItem>
<NGridItem>
<NInput />
</NGridItem>
<NGridItem>
<NDatePicker type="datetimerange" clearable />
</NGridItem>
<NGridItem>
<NInput />
</NGridItem>
<NGridItem>
<NInput />
</NGridItem>
</>
),
}}
</RCollapse>
<RTable
v-model:checkedRowKeys={this.checkedRowKeys}
onUpdateCheckedRowKeys={checkedRowKeysBind.bind(this)}
onRegister={register.bind(this)}
scrollX={1000}
title={
<NFlex align="center">
<span>标题插槽:</span>
<NSwitch
onUpdateValue={(value: boolean) => (this.tableLoading = value)}
></NSwitch>
</NFlex>
}
data={this.tableData}
v-model:columns={this.actionColumns}
pagination={{
pageSize: 10,
}}
contextMenuOptions={this.tableMenuOptions}
loading={this.tableLoading}
onContextMenuClick={this.menuSelect.bind(this)}
toolOptions={[
<NPopover>
{{
trigger: () => (
<RIcon
name="action/search"
size="18"
cursor="pointer"
onClick={() => {
window.$message.info('点击了搜索按钮')
}}
/>
),
default: () => '我是自定义工具栏示例',
}}
</NPopover>,
]}
rowKey={(row) => row.key}
striped
>
{{
tableFooter: () => '表格的底部内容区域插槽,有时候你可能会用上',
tableAction: () => '表格的操作区域内容插槽,有时候可能会用上',
}}
</RTable>
</NFlex>
)
},
})
export default TableView

View File

@ -0,0 +1,57 @@
import { RTablePro } from '@/components'
import { listPeople } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NCheckbox } from 'naive-ui'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoAutoHeight',
setup() {
const { t } = useI18n('table')
const { data } = listPeople()
const virtual = ref(false)
const footer = ref(false)
const action = ref(false)
const columns = computed(() => createPeopleColumns(t))
const ages = [...new Set(data.slice(0, 10).map(({ age }) => age))].sort(
(a, b) => a - b,
)
return () => (
<RTablePro
autoHeight
virtualScroll={virtual.value}
data={data}
columns={columns.value}
scrollX={944}
pageSize={20}
search={[
{ key: 'name', label: t('name'), placeholder: t('nameHint') },
{
key: 'age',
label: t('age'),
options: ages.map((age) => ({ value: age, label: String(age) })),
},
]}
>
{{
toolbar: () => (
<>
<NCheckbox v-model:checked={virtual.value}>
{t('virtualRows')}
</NCheckbox>
<NCheckbox v-model:checked={footer.value}>
{t('showFooter')}
</NCheckbox>
<NCheckbox v-model:checked={action.value}>
{t('showAction')}
</NCheckbox>
</>
),
tableFooter: footer.value ? () => t('footerExample') : void 0,
tableAction: action.value ? () => t('actionExample') : void 0,
}}
</RTablePro>
)
},
})

View File

@ -0,0 +1,28 @@
import { RTablePro } from '@/components'
import { listPeople } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoBasic',
setup() {
const { t } = useI18n('table')
const { data } = listPeople({ page: 1, pageSize: 10 })
const columns = computed(() =>
createPeopleColumns(t).map((column) => {
if ('key' in column && column.key === 'age')
return {
...column,
sorter: (a: (typeof data)[number], b: (typeof data)[number]) =>
a.age - b.age,
}
return column
}),
)
return () => (
<RTablePro bare data={data} columns={columns.value} scrollX={944} />
)
},
})

View File

@ -0,0 +1,49 @@
import { RTablePro } from '@/components'
import { listPeople } from '@/demo-data/people'
import type { Person } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NCheckbox } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoColumns',
setup() {
const { t } = useI18n('table')
const { data } = listPeople()
const showId = ref(true)
const columns = computed<DataTableColumns<Person>>(() =>
[
{ type: 'selection' as const, width: 44 },
{
title: t('contactGroup'),
key: 'contact',
children: [
{ title: t('name'), key: 'name', width: 120 },
{ title: t('email'), key: 'email', width: 250 },
],
},
...createPeopleColumns(t).slice(2),
].filter(
(column) => showId.value || !('key' in column && column.key === 'id'),
),
)
return () => (
<RTablePro
data={data}
columns={columns.value}
columnStateKey="demo:columns"
scrollX={960}
>
{{
title: () => (
<NCheckbox v-model:checked={showId.value}>
{t('includeIdField')}
</NCheckbox>
),
}}
</RTablePro>
)
},
})

View File

@ -0,0 +1,90 @@
import { RTablePro } from '@/components'
import type { TableProInst } from '@/components'
import { listPeople } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NFlex, NInput } from 'naive-ui'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoCustom',
setup() {
const { t } = useI18n('table')
const { data } = listPeople()
const table = shallowRef<TableProInst>()
const email = ref('')
const selected = ref<(string | number)[]>([])
const columns = computed(() => [
{ type: 'selection' as const, width: 44 },
...createPeopleColumns(t),
])
return () => (
<RTablePro
ref={table}
columns={columns.value}
data={data}
v-model:checkedRowKeys={selected.value}
scrollX={944}
contextMenuOptions={[{ label: t('contextAction'), key: 'example' }]}
onContextMenuClick={() => window.$message?.info(t('contextAction'))}
>
{{
filters: ({
submit,
}: {
submit: (values: { email?: string }) => Promise<void>
}) => (
<form
class="r-table-search"
onSubmit={(event) => {
event.preventDefault()
void submit(email.value ? { email: email.value.trim() } : {})
}}
>
<div class="r-table-search__field">
<NInput
inputProps={{ 'aria-label': t('email') }}
v-model:value={email.value}
placeholder={t('emailHint')}
clearable
/>
</div>
<NButton attrType="submit">{t('search')}</NButton>
</form>
),
title: () => (
<NFlex size={6}>
<NButton
size="small"
secondary
onClick={() => table.value?.setPage(1)}
>
{t('firstPage')}
</NButton>
<NButton
size="small"
secondary
onClick={() => table.value?.setPageSize(20)}
>
{t('twentyRows')}
</NButton>
</NFlex>
),
tableFooter: () => t('customFooter'),
tableAction: () => (
<NButton
size="small"
text
disabled={!selected.value.length}
onClick={() => {
selected.value = []
}}
>
{t('clearSelection', { count: selected.value.length })}
</NButton>
),
}}
</RTablePro>
)
},
})

View File

@ -0,0 +1,18 @@
import type { Person } from '@/demo-data/people'
import type { DataTableColumns } from 'naive-ui'
export const createPeopleColumns = (
t: (key: string) => string,
): DataTableColumns<Person> => [
{ title: t('name'), key: 'name', width: 112 },
{ title: t('email'), key: 'email', width: 228, ellipsis: { tooltip: true } },
{
title: t('address'),
key: 'address',
width: 150,
ellipsis: { tooltip: true },
},
{ title: t('age'), key: 'age', width: 72, align: 'right' },
{ title: t('created'), key: 'createDate', width: 128 },
{ title: 'ID', key: 'id', width: 218, ellipsis: { tooltip: true } },
]

View File

@ -0,0 +1,54 @@
import { RTablePro } from '@/components'
import type { TableProInst } from '@/components'
import { listPeople } from '@/demo-data/people'
import { useI18n } from '@/hooks/template/useI18n'
import { NButton } from 'naive-ui'
import { useTemplateRef } from 'vue'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoPrinting',
setup() {
const { t } = useI18n('table')
const { data } = listPeople()
const table = shallowRef<TableProInst>()
const summary = useTemplateRef<HTMLElement>('summary')
return () => (
<RTablePro
ref={table}
title={t('printDemoTitle')}
columns={createPeopleColumns(t)}
data={data}
pageSize={20}
scrollX={920}
search={[{ key: 'name', label: t('name'), placeholder: t('nameHint') }]}
>
{{
toolbar: () => (
<NButton
size="small"
secondary
onClick={() =>
table.value?.print({
target: summary,
title: t('printSummary'),
style:
'.demo-print-summary { border: 1px solid #b7bec6; padding: 12pt; }',
})
}
>
{t('printSummary')}
</NButton>
),
tableFooter: () => (
<section ref="summary" class="demo-print-summary">
<h3>{t('printSummary')}</h3>
<p>{t('printSummaryText')}</p>
</section>
),
}}
</RTablePro>
)
},
})

View File

@ -0,0 +1,110 @@
import { getPersonList } from '@/api/demo/mock/person'
import type { PersonListParams } from '@/api/demo/mock/person'
import { RTablePro } from '@/components'
import type { TableProInst } from '@/components'
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, NTag } from 'naive-ui'
import type { DataTableSortState } from 'naive-ui'
import { createPeopleColumns } from './people'
export default defineComponent({
name: 'TableDemoRemote',
setup() {
const { t } = useI18n('table')
const table = shallowRef<TableProInst>()
const checked = ref<(string | number)[]>([])
const columns = computed(() => [
{ type: 'selection' as const, width: 44 },
...createPeopleColumns(t).map((column) =>
'key' in column && column.key === 'age'
? { ...column, sorter: true }
: column,
),
])
const params = shallowRef<PersonListParams>({})
const updateSorter = (
sorter: DataTableSortState | DataTableSortState[] | null,
) => {
const state = Array.isArray(sorter) ? sorter[0] : sorter
params.value = {
sortAge:
state?.columnKey === 'age' && state.order ? state.order : void 0,
}
}
let failNext = false
const request: typeof getPersonList = (params, signal) => {
if (failNext) {
failNext = false
return Promise.reject(new Error(t('demoFailure')))
}
return getPersonList(params, signal)
}
return () => (
<RTablePro
ref={table}
title={t('directory')}
columns={columns.value}
v-model:checkedRowKeys={checked.value}
allowCheckingNotLoaded
request={request}
params={params.value}
onUpdateSorter={updateSorter}
columnStateKey="demo:remote"
search={[
{ key: 'name', label: t('name'), placeholder: t('nameHint') },
{ key: 'email', label: t('email'), placeholder: t('emailHint') },
]}
scrollX={944}
downloadCsvTableOptions={{ fileName: 'people' }}
>
{{
toolbar: () => (
<>
<NTag size="small" bordered={false} type="info">
{t(import.meta.env.DEV ? 'httpSource' : 'localSource')}
</NTag>
{checked.value.length ? (
<NButton
text
onClick={() => {
checked.value = []
}}
>
{t('clearSelection', { count: checked.value.length })}
</NButton>
) : null}
<NButton
size="small"
secondary
onClick={() => table.value?.downloadCsv()}
>
{t('csv')}
</NButton>
<NButton
size="small"
secondary
onClick={() => table.value?.reload()}
>
{t('reload')}
</NButton>
<NButton
size="small"
quaternary
onClick={() => {
failNext = true
void table.value?.reload()
}}
>
{t('demoFailure')}
</NButton>
</>
),
}}
</RTablePro>
)
},
})

View File

@ -185,7 +185,7 @@ function baseOptions(mode: string): PluginOption[] {
mockDevServerPlugin({
dir: 'mock',
include: ['**/*.mock.ts'],
exclude: ['shared/**'],
prefix: '/api',
awaitInitialLoad: true,
reload: true,
build: true,