跳转到正文

TablePro 在线示例 ​

从纯表格开始,按需加入查询、分页、列设置或打印。以下示例使用 Ray Admin 的真实组件和演示数据,无需登录或连接业务接口。展开「运行示例」后才加载交互区域;窄屏可以在表格内横向滚动,也可以在新标签页打开。每个示例都附实际运行的源码。

想解决的问题建议从这里开始
已经拿到了数据,只想展示纯表格与本地排序
接口返回当前页和总数远端查询与失败恢复
由页面或查询库维护数据和分页手动远端分页
组合筛选、校验和远程选项高级搜索
表格填满工作区,列多或数据多自适应高度与虚拟滚动 · 列设置与缓存
定制操作区,或获取打印和 CSV自定义插槽与行菜单 · 打印与 CSV
从页面其他位置操作表格实例与 Hooks

纯表格与本地排序 ​

点击「年龄」表头,在升序、降序和默认顺序间切换。表格只消费给定的 10 行;bare 隐藏标题和工具栏,并默认关闭分页。宽表通过 scrollX 保留列宽。

运行示例

在新标签页运行此示例

查看纯表格源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoBasic',
  setup() {
    const { t } = useI18n('table')
    const { data, loading } = usePeopleData(() => ({ page: 1, pageSize: 10 }))
    const columns = computed(() =>
      createPeopleColumns(t).map((column) => {
        if ('key' in column && column.key === 'age')
          return {
            ...column,
            sorter: (
              a: (typeof data.value)[number],
              b: (typeof data.value)[number],
            ) => a.age - b.age,
          }

        return column
      }),
    )

    return () => (
      <RTablePro
        bare
        data={data.value}
        loading={loading.value}
        columns={columns.value}
        scrollX={944}
      />
    )
  },
})

远端查询与失败恢复 ​

  1. 复制某行姓名或邮箱的一部分,填入上方筛选区并提交。查询回到第 1 页,分页使用筛选后的总数。
  2. 清除条件后排序「年龄」并翻页。年龄排序通过 onUpdateSorter 转成 params.sortAge,在分页前作用于整个结果集。
  3. 分别在两页勾选行;工具栏显示跨页选中总数。「更多操作 → 导出 CSV」导出当前页可见数据列。
  4. 点击「模拟请求失败」,观察旧行清空和错误提示;点击「刷新」恢复。传给 request 的 signal 可转交给 HTTP 客户端。
运行示例

在新标签页运行此示例

查看远端查询源码
tsx
import { getPersonList } from '@/api/demo/mock/person'
import type { PersonListParams } from '@/api/demo/mock/person'
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import type { TableProInst } from '@ray-template/ui/table-pro'
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('httpSource')}
              </NTag>
              {checked.value.length ? (
                <NButton
                  text
                  onClick={() => {
                    checked.value = []
                  }}
                >
                  {t('clearSelection', { count: checked.value.length })}
                </NButton>
              ) : null}
              <NButton
                size="small"
                quaternary
                onClick={() => {
                  failNext = true
                  void table.value?.reload()
                }}
              >
                {t('demoFailure')}
              </NButton>
            </>
          ),
        }}
      </RTablePro>
    )
  },
})

手动远端分页 ​

此例用本地数据模拟外部接口,只向表格传入当前页。先翻到第 2 页,再按姓名筛选;页码会回到第 1 页,总数随条件更新。改变每页条数也会回到第 1 页。

页面拥有 page、pageSize 和 itemCount,通过分页回调与 onSearch 更新。接入异步服务时,在这一层维护加载、取消和错误;希望由 TablePro 管理这些状态时,使用上一个示例的 request。

运行示例

在新标签页运行此示例

查看受控分页源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoControlled',
  setup() {
    const { t } = useI18n()
    const page = ref(1)
    const pageSize = ref(10)
    const name = ref<string>()
    const { data, total, loading } = usePeopleData(() => ({
      page: page.value,
      pageSize: pageSize.value,
      name: name.value,
    }))
    const columns = computed(() =>
      createPeopleColumns((key) => t(`table.${key}`)),
    )

    return () => (
      <RTablePro
        title={t('menu.TableControlled')}
        remote
        data={data.value}
        loading={loading.value}
        columns={columns.value}
        scrollX={944}
        pagination={{
          page: page.value,
          pageSize: pageSize.value,
          itemCount: total.value,
          showSizePicker: true,
          pageSizes: [10, 20, 50],
          onUpdatePage: (value) => (page.value = value),
          onUpdatePageSize: (value) => {
            pageSize.value = value
            page.value = 1
          },
        }}
        search={{
          fields: [{ key: 'name', label: t('table.name'), type: 'text' }],
        }}
        onSearch={({ values }) => {
          name.value = typeof values.name === 'string' ? values.name : void 0
          page.value = 1
        }}
      />
    )
  },
})

高级搜索 ​

此例可在本地匹配和模拟远端之间切换。每次操作后比较下方的「草稿」「已应用条件」「转换后的参数」和「实际列表请求」:

  1. 组合条件:添加状态多选和创建日期区间后提交。远端请求中的日期会拆成 createdFrom 和 createdTo,翻页继续沿用这些条件。
  2. 联动和取消:快速切换北区和南区。负责人草稿会清空,旧的候选请求会取消。在南区候选项中搜索「王雨」。
  3. 零值与布尔值:点击「交付与金额」,应用条件后展开订单。查看商品级联、仓库树、配送控件和日期时间字段如何配合,确认参数保留 minAmount: 0 与 invoiced: false。
  4. 校验与自动查询:提交单字符关键词,确认旧结果仍在;修正输入后切换为输入后自动应用,连续编辑观察防抖。
  5. 分别恢复失败:让负责人候选或列表失败一次。候选可在字段处重试,列表可再次提交。
运行示例

在新标签页运行此示例

查看高级搜索、业务 API 及演示数据源码
tsx
import './search.scss'
import { apiMockEnabled } from '@/api/admin/client'
import {
  getSearchOptions,
  getSearchOrders,
  getSearchOwners,
} from '@/api/demo/data'
import type { DemoOrder, SearchOptions } from '@/api/demo/data'
import { useSettingGetters } from '@/store'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import type {
  TableProColumn,
  TableProParams,
  TableProRequest,
  TableProSearchOptionContext,
  TableProSearchOptions,
  TableProSearchValues,
} from '@ray-template/ui/table-pro'
import {
  NAlert,
  NButton,
  NCard,
  NCheckbox,
  NFlex,
  NRadio,
  NRadioGroup,
  NTag,
} from 'naive-ui'
import {
  computed,
  defineComponent,
  nextTick,
  ref,
  shallowRef,
  useId,
} from 'vue'
import DemoPage from '../components/DemoPage'
import { searchCopy } from './search-copy'

const initialValues: TableProSearchValues = {}
const pagination = { pageSizes: [5, 10, 20] }
const instantDelay = 350
const extraKeys = [
  'productId',
  'warehouseId',
  'minAmount',
  'invoiced',
  'delivery',
  'deliveryAt',
  'deliveryTime',
] as const

type Trace = {
  id: number
  kind: 'list' | 'owner'
  detail: number | string
  phase: 'pending' | 'success' | 'cancelled' | 'failed'
}

const traceTypes = {
  pending: 'info',
  success: 'success',
  cancelled: 'default',
  failed: 'error',
} as const

const scenarios = ['combine', 'race', 'deliveryRecipe', 'validation'] as const

type Scenario = (typeof scenarios)[number]

function nonemptyValues(values: TableProSearchValues) {
  return Object.fromEntries(
    Object.entries(values).filter(
      ([, value]) =>
        value != null &&
        value !== '' &&
        (!Array.isArray(value) || value.length > 0),
    ),
  )
}

export default defineComponent({
  name: 'TableDemoSearch',
  setup() {
    const { getLocaleLanguage } = useSettingGetters()
    const queryParams = computed(() => ({ locale: getLocaleLanguage.value }))
    const copy = computed(() =>
      getLocaleLanguage.value === 'zh-CN' ? searchCopy.zh : searchCopy.en,
    )
    const options = shallowRef<SearchOptions>()
    const optionsLoading = ref(false)
    const optionsFailed = ref(false)
    const optionsAttempt = ref(0)

    watch(
      [getLocaleLanguage, optionsAttempt],
      async ([locale], _, cleanup) => {
        const controller = new AbortController()

        cleanup(() => controller.abort())
        options.value = void 0
        optionsFailed.value = false
        optionsLoading.value = true

        try {
          const result = await getSearchOptions(locale, controller.signal)

          if (!controller.signal.aborted) options.value = result
        } catch {
          if (!controller.signal.aborted) optionsFailed.value = true
        } finally {
          if (!controller.signal.aborted) optionsLoading.value = false
        }
      },
      { immediate: true },
    )
    const id = useId()
    const [register, table] = useTablePro()
    const source = ref<'local' | 'remote'>('remote')
    const submitMode = ref<'manual' | 'change'>('manual')
    const more = ref(false)
    const scenario = ref<Scenario>()
    const listPayload = shallowRef<TableProParams>({})
    const mapped = shallowRef<Readonly<Record<string, unknown>>>(initialValues)
    const trace = shallowRef<readonly Trace[]>([])
    let requestId = 0
    let failListOnce = false
    let failOwnerOnce = false

    const track = async <T,>(
      kind: Trace['kind'],
      detail: Trace['detail'],
      signal: AbortSignal,
      result: () => Promise<T>,
    ) => {
      const id = ++requestId
      const entry: Trace = { id, kind, detail, phase: 'pending' }

      trace.value = [entry, ...trace.value].slice(0, 6)
      const finish = (phase: Trace['phase']) => {
        trace.value = trace.value.map((entry) =>
          entry.id === id ? { ...entry, phase } : entry,
        )
      }

      try {
        signal.throwIfAborted()
        const value = await result()

        signal.throwIfAborted()

        finish('success')

        return value
      } catch (error) {
        finish(signal.aborted ? 'cancelled' : 'failed')
        throw error
      }
    }

    const rows = shallowRef<DemoOrder[]>([])
    const rowsLoading = ref(false)

    watch(
      [source, getLocaleLanguage],
      async ([mode, locale], _, cleanup) => {
        if (mode !== 'local') return

        const controller = new AbortController()

        cleanup(() => controller.abort())
        rowsLoading.value = true

        try {
          rows.value = (
            await getSearchOrders(
              { page: 1, pageSize: 100 },
              locale,
              controller.signal,
            )
          ).items
        } catch {
          if (!controller.signal.aborted)
            window.$message.error(
              locale === 'zh-CN'
                ? '查询失败,请重试。'
                : 'Query failed. Please retry.',
            )
        } finally {
          if (!controller.signal.aborted) rowsLoading.value = false
        }
      },
      { immediate: true },
    )
    const money = computed(
      () =>
        new Intl.NumberFormat(getLocaleLanguage.value, {
          style: 'currency',
          currency: copy.value.currency,
          maximumFractionDigits: 0,
        }),
    )
    const dateTime = computed(
      () =>
        new Intl.DateTimeFormat(getLocaleLanguage.value, {
          dateStyle: 'medium',
          timeStyle: 'short',
        }),
    )
    const deliveryDetails: TableProColumn = {
      type: 'expand',
      renderExpand: (row: DemoOrder) => {
        const labels = copy.value
        const details = [
          [labels.warehouse, row.warehouse],
          [labels.invoiced, row.invoiced ? labels.yes : labels.no],
          [labels.delivery, row.deliveryLabel],
          [labels.deliveryAt, dateTime.value.format(row.deliveryAt)],
        ]

        return (
          <dl class="r-search-demo__order">
            {details.map(([label, value]) => (
              <div key={label}>
                <dt>{label}</dt>
                <dd>{value}</dd>
              </div>
            ))}
          </dl>
        )
      },
    }
    const columns = computed<TableProColumn[]>(() => [
      ...(more.value ? [deliveryDetails] : []),
      { key: 'orderNo', title: copy.value.order, minWidth: 92 },
      { key: 'product', title: copy.value.product, minWidth: 90 },
      { key: 'statusLabel', title: copy.value.status, minWidth: 82 },
      { key: 'createdAt', title: copy.value.created, minWidth: 108 },
      { key: 'organization', title: copy.value.organization, minWidth: 90 },
      { key: 'owner', title: copy.value.owner, minWidth: 90 },
      {
        key: 'amount',
        title: copy.value.amount,
        minWidth: 85,
        render: (row: Record<string, unknown>) =>
          money.value.format(Number(row.amount)),
      },
    ])

    const draft = computed(() =>
      table.isReady.value ? nonemptyValues(table.getSearchValues()) : {},
    )
    const applied = computed(() =>
      table.isReady.value ? table.getSearchValues('applied') : initialValues,
    )
    const dirty = computed(
      () => JSON.stringify(draft.value) !== JSON.stringify(applied.value),
    )
    const pageRows = computed(() =>
      table.isReady.value ? table.getCurrentPageData().length : 0,
    )
    const showExtra = () => more.value

    const fillDraft = (values: TableProSearchValues) => {
      table.setSearchValues({
        ...Object.fromEntries(
          Object.keys(table.getSearchValues()).map((key) => [key, null]),
        ),
        ...values,
      })
    }

    const loadOwners = ({
      keyword,
      values,
      signal,
    }: TableProSearchOptionContext) => {
      const org = String(values.orgId ?? '')
      const fail = failOwnerOnce

      failOwnerOnce = false

      return track('owner', org, signal, () =>
        getSearchOwners(org, keyword, getLocaleLanguage.value, signal, fail),
      )
    }

    const search = computed<TableProSearchOptions>(() => {
      const labels = copy.value

      return {
        initialValues,
        submitMode: submitMode.value,
        debounce: instantDelay,
        searchText: labels.apply,
        resetText: labels.reset,
        renderActions: ({ defaultActions, submit }) => (
          <>
            <NButton
              text
              attrType="button"
              onClick={() => {
                fillDraft({})
                void submit()
              }}
            >
              {labels.clear}
            </NButton>
            {defaultActions}
          </>
        ),
        fields: [
          {
            key: 'keyword',
            label: labels.keyword,
            type: 'text',
            placeholder: labels.keywordHint,
            getValue: (row) => `${row.orderNo} ${row.product}`,
            rules: {
              trigger: 'blur',
              validator: (_rule, value: unknown) =>
                typeof value !== 'string' ||
                value.trim().length === 0 ||
                value.trim().length >= 2 ||
                new Error(labels.keywordError),
            },
          },
          {
            key: 'status',
            label: labels.status,
            type: 'select',
            multiple: true,
            options: options.value?.statuses ?? [],
          },
          {
            key: 'createdAt',
            label: labels.created,
            type: 'dateRange',
            span: 2,
            transform: ([createdFrom, createdTo]) => ({
              createdFrom,
              createdTo,
            }),
          },
          {
            key: 'orgId',
            label: labels.organization,
            type: 'select',
            options: options.value?.organizations ?? [],
          },
          {
            key: 'ownerId',
            label: labels.owner,
            type: 'select',
            dependsOn: ['orgId'],
            visible: ({ orgId }) => orgId != null,
            loadOptions: loadOwners,
          },
          {
            key: 'productId',
            label: labels.category,
            type: 'cascader',
            visible: showExtra,
            fieldProps: {
              options: options.value?.productCategories ?? [],
            },
          },
          {
            key: 'warehouseId',
            label: labels.warehouse,
            type: 'treeSelect',
            visible: showExtra,
            fieldProps: {
              defaultExpandAll: true,
              keyField: 'value',
              options: (options.value?.warehouseRegions ?? []).map(
                (region) => ({
                  ...region,
                  disabled: true,
                }),
              ),
            },
          },
          {
            key: 'minAmount',
            label: labels.minAmount,
            type: 'number',
            visible: showExtra,
            fieldProps: { min: 0, step: 50 },
            getValue: (row) => row.amount,
            matches: (cell, minimum) =>
              typeof cell === 'number' && cell >= minimum,
          },
          {
            key: 'invoiced',
            label: labels.invoiced,
            type: 'boolean',
            visible: showExtra,
          },
          {
            key: 'delivery',
            label: labels.delivery,
            type: 'custom',
            visible: showExtra,
            render: ({ inputId, labelId, value, setValue }) => (
              <NRadioGroup
                name={inputId}
                aria-labelledby={labelId}
                value={typeof value === 'string' ? value : 'any'}
                onUpdateValue={(next) => setValue(next === 'any' ? null : next)}
              >
                <NFlex size="small">
                  <NRadio value="any">{labels.any}</NRadio>
                  {options.value?.deliveries.map((option) => (
                    <NRadio key={option.value} value={option.value}>
                      {option.label}
                    </NRadio>
                  ))}
                </NFlex>
              </NRadioGroup>
            ),
          },
          {
            key: 'deliveryAt',
            label: labels.deliveryAt,
            type: 'datetimeRange',
            span: 2,
            visible: showExtra,
            transform: ([deliveryFrom, deliveryTo]) => ({
              deliveryFrom,
              deliveryTo,
            }),
          },
          {
            key: 'deliveryTime',
            label: labels.deliveryTime,
            type: 'time',
            visible: showExtra,
          },
        ],
      }
    })

    const request: TableProRequest = (query, signal) => {
      const { page = 1, pageSize = 5 } = query
      const fail = failListOnce

      listPayload.value = query
      failListOnce = false

      return track('list', page, signal, async () => {
        const result = await getSearchOrders(
          query,
          getLocaleLanguage.value,
          signal,
          fail,
        )

        return { data: result.items, total: result.total }
      })
    }

    const startScenario = async (next: Scenario) => {
      scenario.value = next
      more.value = next === 'deliveryRecipe'

      switch (next) {
        case 'combine':
          fillDraft({
            status: ['pending', 'paid'],
            createdAt: ['2026-11-01', '2026-11-08'],
          })
          break
        case 'race':
          fillDraft({})
          await nextTick()
          table.setSearchValues({ orgId: 'north', ownerId: 'n1' })
          await nextTick()
          table.setSearchValues({ orgId: 'south' })
          break
        case 'deliveryRecipe':
          fillDraft({
            productId: 'notebook',
            warehouseId: 'north-main',
            minAmount: 0,
            invoiced: false,
            delivery: 'express',
            deliveryAt: [
              new Date(2026, 10, 2).getTime(),
              new Date(2026, 10, 10, 23, 59).getTime(),
            ],
            deliveryTime: '09:00:00',
          })
          break
        default:
          fillDraft({ keyword: 'O' })
          await table.submitSearch()
          break
      }
    }

    const failList = () => {
      failListOnce = true
      void table.reload()
    }
    const failOwner = () => {
      failOwnerOnce = true
      table.setSearchValues({
        orgId: options.value?.organizations.find(
          ({ value }) => value !== draft.value.orgId,
        )?.value,
      })
    }

    const scenarioHint = computed(
      () =>
        ({
          combine: copy.value.combineHint,
          race: copy.value.raceHint,
          deliveryRecipe: copy.value.deliveryHint,
          validation: copy.value.validationHint,
        })[scenario.value ?? 'combine'],
    )

    return () => {
      const labels = copy.value
      const query = table.queryState.value
      const output =
        source.value === 'remote'
          ? ([labels.payload, listPayload.value] as const)
          : ([labels.mapped, mapped.value] as const)

      return (
        <DemoPage title={labels.title} description={labels.description}>
          <NCard size="small">
            <div class="r-search-demo__guide">
              {optionsFailed.value && (
                <NAlert type="error" title={labels.optionsFailed}>
                  <NButton size="small" onClick={() => optionsAttempt.value++}>
                    {labels.retryOptions}
                  </NButton>
                </NAlert>
              )}
              {apiMockEnabled && <strong>{labels.tryScenario}</strong>}
              {apiMockEnabled && (
                <NFlex size="small">
                  {scenarios.map((key) => (
                    <NButton
                      key={key}
                      size="small"
                      secondary
                      type={scenario.value === key ? 'primary' : 'default'}
                      disabled={
                        !table.isReady.value ||
                        optionsLoading.value ||
                        optionsFailed.value
                      }
                      onClick={() => void startScenario(key)}
                    >
                      {labels[key]}
                    </NButton>
                  ))}
                </NFlex>
              )}
              {scenario.value && <p role="status">{scenarioHint.value}</p>}
              <div class="r-search-demo__settings">
                <NRadioGroup
                  name={`${id}-source`}
                  aria-label={labels.source}
                  value={source.value}
                  onUpdateValue={(value) => {
                    source.value = value === 'remote' ? 'remote' : 'local'
                  }}
                >
                  <NFlex size="small">
                    <NRadio value="local">{labels.local}</NRadio>
                    <NRadio value="remote">{labels.remote}</NRadio>
                  </NFlex>
                </NRadioGroup>
                <NRadioGroup
                  name={`${id}-mode`}
                  aria-label={labels.submitMode}
                  value={submitMode.value}
                  onUpdateValue={(value) => {
                    submitMode.value = value === 'change' ? 'change' : 'manual'
                  }}
                >
                  <NFlex size="small">
                    <NRadio value="manual">{labels.manual}</NRadio>
                    <NRadio value="change">{labels.instant}</NRadio>
                  </NFlex>
                </NRadioGroup>
              </div>
              <p>
                {submitMode.value === 'manual'
                  ? labels.manualHint
                  : labels.instantHint}
              </p>
              <NCheckbox
                checked={more.value}
                onUpdateChecked={(checked) => {
                  more.value = checked

                  if (!checked)
                    table.setSearchValues(
                      Object.fromEntries(extraKeys.map((key) => [key, null])),
                    )
                }}
              >
                {labels.more}
              </NCheckbox>
            </div>
          </NCard>

          <RTablePro
            onRegister={register}
            columns={columns.value}
            search={search.value}
            data={source.value === 'local' ? rows.value : void 0}
            request={source.value === 'remote' ? request : void 0}
            params={queryParams.value}
            loading={
              optionsLoading.value ||
              (source.value === 'local' && rowsLoading.value)
            }
            pageSize={5}
            pagination={pagination}
            scrollX={more.value ? 700 : 645}
            tool={false}
            onSearch={({ params }) => {
              mapped.value = params
            }}
          />

          <div role="status">
            <NFlex size="small" align="center">
              <NTag size="small" type={dirty.value ? 'warning' : 'success'}>
                {dirty.value ? labels.dirty : labels.clean}
              </NTag>
              <NTag size="small">{labels.pageRows(pageRows.value)}</NTag>
              {query?.total != null && (
                <NTag size="small">{labels.matchedRows(query.total)}</NTag>
              )}
            </NFlex>
          </div>

          <details class="r-search-demo__details" open>
            <summary>{labels.inspector}</summary>
            <div class="r-search-demo__values">
              {(
                [
                  [labels.draft, draft.value],
                  [labels.applied, applied.value],
                  output,
                ] as const
              ).map(([label, values]) => (
                <div class="r-demo-result" key={label}>
                  <span class="r-demo-result__label">{label}</span>
                  <div class="r-demo-result__value">
                    <pre>{JSON.stringify(values, null, 2)}</pre>
                  </div>
                </div>
              ))}
            </div>
          </details>

          {apiMockEnabled && (
            <NCard size="small">
              <div class="r-search-demo__trace-head">
                <strong>{labels.trace}</strong>
                <NFlex size="small">
                  <NButton
                    size="small"
                    secondary
                    disabled={!table.isReady.value}
                    onClick={failOwner}
                  >
                    {labels.failOwner}
                  </NButton>
                  {source.value === 'remote' && (
                    <NButton
                      size="small"
                      secondary
                      disabled={!table.isReady.value || query?.loading}
                      onClick={failList}
                    >
                      {labels.failList}
                    </NButton>
                  )}
                </NFlex>
              </div>
              {trace.value.length ? (
                <ol class="r-search-demo__trace" aria-label={labels.trace}>
                  {trace.value.map(({ id, kind, detail, phase }) => (
                    <li key={id}>
                      <span>
                        {kind === 'list'
                          ? labels.listRequest
                          : labels.ownerRequest}
                      </span>
                      <span>
                        {typeof detail === 'number'
                          ? labels.page(detail)
                          : (options.value?.organizations.find(
                              ({ value }) => value === detail,
                            )?.label ?? detail)}
                      </span>
                      <NTag size="small" type={traceTypes[phase]}>
                        {labels.phases[phase]}
                      </NTag>
                    </li>
                  ))}
                </ol>
              ) : (
                <p class="r-search-demo__empty">{labels.emptyTrace}</p>
              )}
            </NCard>
          )}
        </DemoPage>
      )
    }
  },
})
ts
import { adminRequest } from '@/api/admin/client'
import {
  chartsSchema,
  ordersResultSchema,
  ownerOptionsSchema,
  routeDemoPersonSchema,
  routePeopleResultSchema,
  searchOptionsSchema,
} from './contracts'
import type { DemoOrderQuery, RoutePeopleQuery } from './contracts'

export * from './contracts'

export const getSearchOrders = (
  query: DemoOrderQuery,
  locale: string,
  signal?: AbortSignal,
  fail = false,
) =>
  adminRequest('demo/orders/search', ordersResultSchema, {
    method: 'post',
    data: { query, locale, fail },
    signal,
  })
export const getSearchOwners = (
  orgId: string,
  keyword: string,
  locale: string,
  signal: AbortSignal,
  fail = false,
) =>
  adminRequest('demo/owners/search', ownerOptionsSchema, {
    method: 'post',
    data: { orgId, keyword, locale, fail },
    signal,
  })
export const getDemoCharts = (refresh = false, signal?: AbortSignal) =>
  adminRequest('demo/charts', chartsSchema, {
    method: 'get',
    params: { refresh },
    signal,
  })

export const getSearchOptions = (locale: string, signal?: AbortSignal) =>
  adminRequest('demo/search-options', searchOptionsSchema, {
    method: 'get',
    params: { locale },
    signal,
  })

export const getRouteDemoPeople = (
  params: RoutePeopleQuery = {},
  signal?: AbortSignal,
) =>
  adminRequest('demo/route-people', routePeopleResultSchema, {
    method: 'get',
    params,
    signal,
  })

export const getRouteDemoPerson = (id: string, signal?: AbortSignal) =>
  adminRequest(
    `demo/route-people/${encodeURIComponent(id)}`,
    routeDemoPersonSchema,
    {
      method: 'get',
      signal,
    },
  )
ts
import type {
  DemoOrder,
  DemoOrderQuery,
  SearchOptions,
} from '@ray-template/api-contracts/demo'

export const statuses = ['pending', 'paid', 'closed'] as const
export const organizations = ['north', 'south'] as const
export const products = ['notes', 'keyboard', 'notebook', 'monitor'] as const
export const warehouses = [
  'north-main',
  'north-backup',
  'south-main',
  'south-backup',
] as const
export const owners = [
  { id: 'n1', orgId: 'north' },
  { id: 'n2', orgId: 'north' },
  { id: 's1', orgId: 'south' },
  { id: 's2', orgId: 'south' },
] as const

const labels = {
  'zh-CN': {
    teams: ['北区', '南区'],
    people: ['陈晨', '林岚', '周宁', '王雨'],
    statuses: ['待处理', '已支付', '已关闭'],
    products: ['便签', '键盘', '笔记本', '显示器'],
    groups: ['办公用品', '电子设备'],
    warehouses: ['北区主仓', '北区备仓', '南区主仓', '南区备仓'],
    deliveries: ['普通', '加急'],
  },
  'en-US': {
    teams: ['North', 'South'],
    people: ['Chen', 'Lin', 'Zhou', 'Wang'],
    statuses: ['Pending', 'Paid', 'Closed'],
    products: ['Notes', 'Keyboard', 'Notebook', 'Monitor'],
    groups: ['Office supplies', 'Electronics'],
    warehouses: ['North main', 'North backup', 'South main', 'South backup'],
    deliveries: ['Standard', 'Express'],
  },
}

export const getOrderLabels = (locale: string) =>
  labels[locale === 'zh-CN' ? 'zh-CN' : 'en-US']

export function getOrderOptions(locale: string): SearchOptions {
  const copy = getOrderLabels(locale)

  return {
    statuses: statuses.map((value, index) => ({
      value,
      label: copy.statuses[index],
    })),
    organizations: organizations.map((value, index) => ({
      value,
      label: copy.teams[index],
    })),
    productCategories: copy.groups.map((label, group) => ({
      value: `category-${group}`,
      label,
      children: products
        .slice(group * 2, group * 2 + 2)
        .map((value, index) => ({
          value,
          label: copy.products[group * 2 + index],
        })),
    })),
    warehouseRegions: organizations.map((value, region) => ({
      value,
      label: copy.teams[region],
      children: warehouses
        .slice(region * 2, region * 2 + 2)
        .map((value, index) => ({
          value,
          label: copy.warehouses[region * 2 + index],
        })),
    })),
    deliveries: ['standard', 'express'].map((value, index) => ({
      value,
      label: copy.deliveries[index],
    })),
  }
}

export const orders = Array.from({ length: 96 }, (_, index) => {
  const ownerIndex = index % owners.length
  const { orgId, id: ownerId } = owners[ownerIndex]
  const productIndex = Math.floor(index / 3) % products.length
  const statusIndex = index % statuses.length
  const warehouseIndex = Math.floor(index / 8) % warehouses.length
  const day = 1 + (index % 12)
  const hour = index % 3 === 0 ? 9 : 14

  return {
    id: index + 1,
    orderNo: `ORD-${String(index + 1).padStart(3, '0')}`,
    productIndex,
    productId: products[productIndex],
    statusIndex,
    status: statuses[statusIndex],
    createdAt: `2026-11-${String(day).padStart(2, '0')}`,
    orgId,
    ownerId,
    ownerIndex,
    warehouseIndex,
    warehouseId: warehouses[warehouseIndex],
    amount: [0, 59, 129, 199, 349, 699, 1299, 2499][index % 8],
    invoiced: Math.floor(index / 4) % 2 === 0,
    delivery: index % 3 === 0 ? 'express' : 'standard',
    deliveryAt: new Date(2026, 10, day + 1, hour).getTime(),
    deliveryTime: hour === 9 ? '09:00:00' : '14:00:00',
  }
})

export function orderMatchesQuery(row: DemoOrder, query: DemoOrderQuery) {
  const {
    keyword,
    status,
    createdFrom,
    createdTo,
    orgId,
    ownerId,
    productId,
    warehouseId,
    minAmount,
    invoiced,
    delivery,
    deliveryFrom,
    deliveryTo,
    deliveryTime,
  } = query

  return (
    `${row.orderNo} ${row.product}`
      .toLowerCase()
      .includes(String(keyword ?? '').toLowerCase()) &&
    (!status?.length || status.includes(row.status)) &&
    (typeof createdFrom !== 'string' || row.createdAt >= createdFrom) &&
    (typeof createdTo !== 'string' || row.createdAt <= createdTo) &&
    (orgId == null || row.orgId === orgId) &&
    (ownerId == null || row.ownerId === ownerId) &&
    (productId == null || row.productId === productId) &&
    (warehouseId == null || row.warehouseId === warehouseId) &&
    (typeof minAmount !== 'number' || row.amount >= minAmount) &&
    (invoiced == null || row.invoiced === invoiced) &&
    (delivery == null || row.delivery === delivery) &&
    (typeof deliveryFrom !== 'number' || row.deliveryAt >= deliveryFrom) &&
    (typeof deliveryTo !== 'number' || row.deliveryAt <= deliveryTo) &&
    (deliveryTime == null || row.deliveryTime === deliveryTime)
  )
}

自适应高度与虚拟滚动 ​

打开虚拟滚动,再分别显示表格底部和操作区。列表区域会为新增内容让出高度,分页留在表格下方。在新标签页改变窗口高度,对比搜索区展开与收起时的可用空间。虚拟滚动仅减少渲染的行;当前页、已加载数据和导出范围仍按原规则计算。

运行示例

在新标签页运行此示例

查看自适应高度源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import { NCheckbox } from 'naive-ui'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoAutoHeight',
  setup() {
    const { t } = useI18n('table')
    const { data, loading } = usePeopleData()
    const virtual = ref(false)
    const footer = ref(false)
    const action = ref(false)
    const columns = computed(() => createPeopleColumns(t))
    const ages = computed(() =>
      [...new Set(data.value.slice(0, 10).map(({ age }) => age))].sort(
        (a, b) => a - b,
      ),
    )

    return () => (
      <RTablePro
        autoHeight
        virtualScroll={virtual.value}
        data={data.value}
        loading={loading.value}
        columns={columns.value}
        scrollX={944}
        pageSize={20}
        search={[
          { key: 'name', label: t('name'), placeholder: t('nameHint') },
          {
            key: 'age',
            label: t('age'),
            options: ages.value.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>
    )
  },
})

列设置与缓存 ​

  1. 打开工具栏的列设置。分别隐藏「姓名」和「邮箱」;两个子列都隐藏后,「联系方式」组标题也会消失。
  2. 拖动根列,或用上下移动按钮排序。带宽度的列可固定到首尾;打开可调宽后,在表头拖动列边界。
  3. 点击恢复列布局,顺序、固定位置和宽度设置回到初始布局,显隐选择保留。
  4. 在新标签页运行示例,隐藏一列后刷新同一标签页;columnStateKey 保存显隐。示例使用独立会话缓存。正式应用可在 key 中加入租户或账户标识。
  5. 切换「启用 ID 字段」查看业务列定义变化。数据列和分组使用稳定 key,选择列不进入可见数据列设置。
运行示例

在新标签页运行此示例

查看列设置源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import type { Person } from '@ray-template/api-contracts/demo'
import { RTablePro } from '@ray-template/ui/table-pro'
import { NCheckbox } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoColumns',
  setup() {
    const { t } = useI18n('table')
    const { data, loading } = usePeopleData()
    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.value}
        loading={loading.value}
        columns={columns.value}
        columnStateKey="demo:columns"
        scrollX={960}
      >
        {{
          title: () => (
            <NCheckbox v-model:checked={showId.value}>
              {t('includeIdField')}
            </NCheckbox>
          ),
        }}
      </RTablePro>
    )
  },
})

自定义插槽与行菜单 ​

在自定义表单里用邮箱筛选,表单通过 filters 插槽的 submit(values) 提交。尝试用标题区的按钮回到第 1 页、改成每页 20 条,再勾选行并用底部动作清除。右键点击某行可执行示例菜单动作,回调会收到该行的数据。

运行示例

在新标签页运行此示例

查看自定义插槽源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import { NButton, NFlex, NInput } from 'naive-ui'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoCustom',
  setup() {
    const { t } = useI18n('table')
    const { data, loading } = usePeopleData()
    const [register, { setPage, setPageSize }] = useTablePro()
    const email = ref('')
    const selected = ref<(string | number)[]>([])
    const columns = computed(() => [
      { type: 'selection' as const, width: 44 },
      ...createPeopleColumns(t),
    ])

    return () => (
      <RTablePro
        onRegister={register}
        columns={columns.value}
        data={data.value}
        loading={loading.value}
        v-model:checkedRowKeys={selected.value}
        scrollX={944}
        contextMenuOptions={[{ label: t('contextAction'), key: 'example' }]}
        onContextMenuClick={(_key, _option, { row }) =>
          window.$message?.info(`${t('contextAction')}: ${row.name}`)
        }
      >
        {{
          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={() => setPage(1)}>
                {t('firstPage')}
              </NButton>
              <NButton size="small" secondary onClick={() => 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>
    )
  },
})

复制图片 ​

在上方任意完整表格点击「复制表格图片」,再粘贴到支持图片的聊天或文档。可先在列设置中隐藏、固定列,或横向滚动后复制,对比当前表格可视区域。虚拟滚动只复制当前已渲染的可视内容;不会补齐全部行。入口默认显示,可用 showCopyImage={false} 隐藏;打印入口仍然默认隐藏。

打印与 CSV ​

本例显式设置 showPrint。先按姓名筛选,或在列设置中隐藏一列,再点击「更多操作 → 打印表格」,预览当前页可见数据列;默认表格不会显示打印入口。点击「打印独立摘要」可预览 print({ target }) 指向的自定义区域。只需查看时,在浏览器的打印对话框选择取消即可。

运行示例

在新标签页运行此示例

查看打印及其样式源码
tsx
import './printing.scss'
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import type { TableProInst } from '@ray-template/ui/table-pro'
import { NButton } from 'naive-ui'
import { useTemplateRef } from 'vue'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoPrinting',
  setup() {
    const { t } = useI18n('table')
    const { data, loading } = usePeopleData()
    const table = shallowRef<TableProInst>()
    const summary = useTemplateRef<HTMLElement>('summary')

    return () => (
      <RTablePro
        ref={table}
        title={t('printDemoTitle')}
        columns={createPeopleColumns(t)}
        data={data.value}
        loading={loading.value}
        showPrint
        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'),
                })
              }
            >
              {t('printSummary')}
            </NButton>
          ),
          tableFooter: () => (
            <section ref="summary" class="demo-print-summary">
              <h3>{t('printSummary')}</h3>
              <p>{t('printSummaryText')}</p>
            </section>
          ),
        }}
      </RTablePro>
    )
  },
})
scss
.demo-print-summary {
  padding: 12pt;
  border: 1px solid var(--r-control-border, ButtonBorder);
  border-radius: var(--r-control-radius, 4px);
  break-inside: avoid;
}

如需比较 CSV 的两种范围,在下方的导出与打印的实例生命周期例子中下载并打开两个文件。

实例与 Hooks ​

查询、重试与分页 ​

先切到第 2 页,再比较「刷新当前页」和「回首页并刷新」。使用模拟失败按钮观察 queryState 的加载、失败和总数变化,并用刷新恢复。提交姓名条件后,示例会显示实际发出的参数。快速切换页码可以观察最新请求的结果。

运行示例

在新标签页运行此示例

查看查询 Hook 源码
tsx
import { apiMockEnabled } from '@/api/admin/client'
import { getPersonList } from '@/api/demo/mock/person'
import type { PersonListParams } from '@/api/demo/mock/person'
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import {
  NButton,
  NCard,
  NFlex,
  NInput,
  NStatistic,
  NTag,
  NText,
} from 'naive-ui'
import { useId } from 'vue'
import DemoPage from '../components/DemoPage'
import { createPeopleColumns } from './people'

const statusColors = {
  idle: 'default',
  loading: 'info',
  failed: 'error',
  loaded: 'success',
} as const

export default defineComponent({
  name: 'TableDemoHooksQuery',
  setup() {
    const { t } = useI18n()
    const [register, { isReady, queryState, reload, setPage, setPageSize }] =
      useTablePro()
    const inputId = useId()
    const nameDraft = ref('')
    const params = shallowRef<PersonListParams>({})
    const lastRequest = shallowRef<PersonListParams>({})
    const attempts = ref(0)
    const columns = computed(() =>
      createPeopleColumns((key) => t(`table.${key}`)).slice(0, 4),
    )
    const phase = computed(() => {
      if (queryState.value?.loading) return 'loading'

      if (queryState.value?.failed) return 'failed'

      return queryState.value?.total != null ? 'loaded' : 'idle'
    })

    let failNext = false
    const request = async (query: PersonListParams, signal: AbortSignal) => {
      const shouldFail = failNext

      failNext = false
      attempts.value += 1
      lastRequest.value = query

      return getPersonList({ ...query, fail: shouldFail }, signal)
    }

    const applyName = (value: string) => {
      if (!isReady.value) return

      const name = value.trim() || void 0

      if (name === params.value.name) {
        void reload(true)
      } else {
        // params 变化已经会回到第一页请求,避免再手动刷新一次。
        params.value = { name }
      }
    }

    return () => (
      <DemoPage
        title={t('menu.TableHooksQuery')}
        description={t('tableHooks.queryDescription')}
      >
        <NCard>
          <NFlex vertical>
            <form
              class="r-table-search"
              onSubmit={(event) => {
                event.preventDefault()
                applyName(nameDraft.value)
              }}
            >
              <div class="r-table-search__field">
                <label for={inputId}>{t('table.name')}</label>
                <NInput
                  inputProps={{ id: inputId, name: 'name' }}
                  v-model:value={nameDraft.value}
                  placeholder={t('table.nameHint')}
                />
              </div>
              <div class="r-table-search__actions">
                <NButton
                  attrType="submit"
                  type="primary"
                  disabled={!isReady.value}
                >
                  {t('table.search')}
                </NButton>
                <NButton
                  disabled={!isReady.value}
                  onClick={() => {
                    nameDraft.value = ''
                    applyName('')
                  }}
                >
                  {t('table.reset')}
                </NButton>
              </div>
            </form>
            <NFlex>
              <NButton disabled={!isReady.value} onClick={() => reload()}>
                {t('tableHooks.reloadPage')}
              </NButton>
              <NButton disabled={!isReady.value} onClick={() => reload(true)}>
                {t('tableHooks.reloadFirstPage')}
              </NButton>
              <NButton disabled={!isReady.value} onClick={() => setPage(2)}>
                {t('tableHooks.secondPage')}
              </NButton>
              <NButton
                disabled={!isReady.value}
                onClick={() => setPageSize(20)}
              >
                {t('table.twentyRows')}
              </NButton>
              {apiMockEnabled && (
                <NButton
                  disabled={!isReady.value || queryState.value?.loading}
                  onClick={() => {
                    failNext = true
                    void reload()
                  }}
                >
                  {t('table.demoFailure')}
                </NButton>
              )}
            </NFlex>
          </NFlex>
        </NCard>
        <NCard title={t('tableHooks.queryStatus')}>
          {{
            'header-extra': () => (
              <NTag
                size="small"
                type={statusColors[phase.value]}
                bordered={false}
              >
                {t(`tableHooks.queryPhase.${phase.value}`)}
              </NTag>
            ),
            default: () => (
              <NFlex vertical size={12}>
                <NFlex size={[24, 12]}>
                  <NStatistic
                    tabularNums
                    label={t('tableHooks.currentPage')}
                    value={queryState.value?.page ?? '—'}
                  />
                  <NStatistic
                    tabularNums
                    label={t('tableHooks.rowsPerPage')}
                    value={queryState.value?.pageSize ?? '—'}
                  />
                  <NStatistic
                    tabularNums
                    label={t('tableHooks.resultTotal')}
                    value={queryState.value?.total ?? '—'}
                  />
                </NFlex>
                <NText depth={3}>
                  {t('tableHooks.lastRequest')}
                  {' · '}
                  {t('tableHooks.requestDetails', {
                    count: attempts.value,
                    page: lastRequest.value.page ?? '—',
                    size: lastRequest.value.pageSize ?? '—',
                    name: lastRequest.value.name ?? '—',
                  })}
                </NText>
              </NFlex>
            ),
          }}
        </NCard>
        <RTablePro
          onRegister={register}
          title={t('table.directory')}
          columns={columns.value}
          request={request}
          params={params.value}
          scrollX={562}
        />
      </DemoPage>
    )
  },
})

跨页选择与批量操作 ​

在两页分别点「选中本页」,再点「取消本页选择」。只有该页的 key 会被移除;对其余行批量标记后,返回相应页面核对结果。排序后点「清除排序」,查看如何调用 getTableInstance() 暴露的底层方法。

运行示例

在新标签页运行此示例

查看选择 Hook 源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import type { Person } from '@ray-template/api-contracts/demo'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import { NButton, NFlex } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoHooksSelection',
  setup() {
    const { t } = useI18n()
    const [register, { isReady, getCurrentPageData, getTableInstance }] =
      useTablePro()
    const { data, loading } = usePeopleData()
    const checked = ref<(string | number)[]>([])
    const marked = shallowRef(new Set<string | number>())
    const columns = computed<DataTableColumns<Person>>(() => [
      { type: 'selection', width: 44 },
      ...createPeopleColumns((key) => t(`table.${key}`))
        .slice(0, 4)
        .map((column) =>
          'key' in column && column.key === 'age'
            ? {
                ...column,
                sorter: (left: Person, right: Person) => left.age - right.age,
              }
            : column,
        ),
      {
        title: t('tableHooks.markColumn'),
        key: 'marked',
        width: 110,
        render: ({ id }) =>
          t(marked.value.has(id) ? 'tableHooks.marked' : 'tableHooks.unmarked'),
      },
    ])

    const currentKeys = () =>
      getCurrentPageData()
        .map((row) => row.id)
        .filter((id): id is string => typeof id === 'string')

    const selectPage = () => {
      checked.value = [...new Set([...checked.value, ...currentKeys()])]
    }
    const unselectPage = () => {
      const pageKeys = new Set<string | number>(currentKeys())

      checked.value = checked.value.filter((id) => !pageKeys.has(id))
    }
    const markSelected = () => {
      marked.value = new Set([...marked.value, ...checked.value])
      checked.value = []
    }

    return () => (
      <DemoPage
        title={t('menu.TableHooksSelection')}
        description={t('tableHooks.selectionDescription')}
      >
        <NFlex>
          <NButton
            type="primary"
            disabled={!isReady.value}
            onClick={selectPage}
          >
            {t('tableHooks.selectPage')}
          </NButton>
          <NButton
            disabled={!isReady.value || !checked.value.length}
            onClick={unselectPage}
          >
            {t('tableHooks.unselectPage')}
          </NButton>
          <NButton
            disabled={!checked.value.length}
            onClick={() => {
              checked.value = []
            }}
          >
            {t('tableHooks.clearAll')}
          </NButton>
          <NButton disabled={!checked.value.length} onClick={markSelected}>
            {t('tableHooks.markSelected')}
          </NButton>
          <NButton
            disabled={!isReady.value}
            onClick={() => getTableInstance()?.clearSorter()}
          >
            {t('tableHooks.clearSort')}
          </NButton>
        </NFlex>
        <DemoResult label={t('tableHooks.selectionResult')}>
          {t('tableHooks.selectionDetails', {
            selected: checked.value.length,
            marked: marked.value.size,
          })}
        </DemoResult>
        <RTablePro
          onRegister={register}
          title={t('table.directory')}
          columns={columns.value}
          data={data.value}
          loading={loading.value}
          v-model:checkedRowKeys={checked.value}
          search={[
            {
              key: 'name',
              label: t('table.name'),
              placeholder: t('table.nameHint'),
            },
          ]}
          scrollX={716}
        />
      </DemoPage>
    )
  },
})

导出与打印的实例生命周期 ​

下载「导出当前页 CSV」和「导出全部已加载数据 CSV」并比较行数。前者只包含当前页,后者使用 keepOriginalData 导出传入表格的整批数据;远端模式下它不会自动请求其他页。点击卸载后观察操作按钮禁用,重新挂载会再次注册实例。

运行示例

在新标签页运行此示例

查看输出 Hook 源码
tsx
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import { NButton, NFlex } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import { createPeopleColumns } from './people'
import { usePeopleData } from './usePeopleData'

export default defineComponent({
  name: 'TableDemoHooksOutput',
  setup() {
    const { t } = useI18n()
    const [register, { isReady, downloadCsv, print }] = useTablePro()
    const { data, loading } = usePeopleData()
    const mounted = ref(true)
    const printResult = ref<boolean>()
    const columns = computed(() =>
      createPeopleColumns((key) => t(`table.${key}`)).slice(0, 4),
    )

    return () => (
      <DemoPage
        title={t('menu.TableHooksOutput')}
        description={t('tableHooks.outputDescription')}
      >
        <NFlex>
          <NButton
            onClick={() => {
              mounted.value = !mounted.value
              printResult.value = void 0
            }}
          >
            {t(mounted.value ? 'tableHooks.unmount' : 'tableHooks.mount')}
          </NButton>
          <NButton
            disabled={!isReady.value}
            onClick={() => downloadCsv({ fileName: 'people-page' })}
          >
            {t('tableHooks.csvPage')}
          </NButton>
          <NButton
            disabled={!isReady.value}
            onClick={() =>
              downloadCsv({ fileName: 'people-loaded', keepOriginalData: true })
            }
          >
            {t('tableHooks.csvLoaded')}
          </NButton>
          <NButton
            disabled={!isReady.value}
            onClick={async () => {
              printResult.value = await print({
                title: t('table.printDemoTitle'),
              })
            }}
          >
            {t('table.printDemoTitle')}
          </NButton>
        </NFlex>
        <DemoResult
          label={t('tableHooks.mountStatus')}
          error={printResult.value === false}
        >
          {t(isReady.value ? 'tableHooks.ready' : 'tableHooks.notReady')}
          {printResult.value === void 0 ? null : (
            <div>
              {t(
                printResult.value
                  ? 'tableHooks.printOpened'
                  : 'table.printError',
              )}
            </div>
          )}
        </DemoResult>
        {mounted.value ? (
          <RTablePro
            onRegister={register}
            title={t('table.directory')}
            columns={columns.value}
            data={data.value}
            loading={loading.value}
            search={[
              {
                key: 'name',
                label: t('table.name'),
                placeholder: t('table.nameHint'),
              },
            ]}
            columnStateKey="demo:hooks-output"
            scrollX={562}
          />
        ) : null}
      </DemoPage>
    )
  },
})

返回 TablePro API 参考