Skip to content
ReferenceVersion 6.0.2

TablePro Live Examples ​

Start with a bare table and add queries, pagination, column settings, or printing as needed. These examples use real Ray Admin components and demo data. Run example loads each interactive area without sign-in or a business API. On narrow screens, scroll inside the table or open a new tab. Each example includes the source that actually runs.

GoalStart here
Display rows you already haveBare table and local sorting
Use the current page and total returned by an APIRemote queries and retry
Let a page or query library own data and paginationManual remote pagination
Combine filters, validation, and remote optionsAdvanced search
Fill the workspace and handle many columns or rowsAutomatic height and virtual scrolling · Column settings and persistence
Customize actions or export print and CSVCustom slots and row menu · Printing and CSV
Control the table from the pageInstance methods and hooks

Bare table and local sorting ​

Click Age to cycle through ascending, descending, and default order. The table consumes the ten supplied rows. bare hides the title and toolbar and disables pagination by default. scrollX preserves column widths in a wide table.

Run example

Run this example in a new tab

View the bare table source
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}
      />
    )
  },
})

Remote queries and retry ​

  1. Copy part of a row's name or email into the filter area and submit. The query returns to page 1 and pagination uses the filtered total.
  2. Clear the filters, sort by Age, and change pages. onUpdateSorter maps the sort to params.sortAge, which applies to the full result set before pagination.
  3. Select rows on two pages. The toolbar shows the total across pages. More actions → Export CSV exports visible data columns on the current page.
  4. Click Simulate request failure to see the old rows clear and an error appear. Click Refresh to recover. Forward request's signal to the HTTP client for cancellation.
Run example

Run this example in a new tab

View the remote query source
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>
    )
  },
})

Manual remote pagination ​

This example simulates an external API with local data and supplies only the current page. Go to page 2 and filter by name. The page returns to 1 and the total changes. Changing page size also returns to page 1.

The page owns page, pageSize, and itemCount and updates them from pagination callbacks and onSearch. For an async service, manage loading, cancellation, and errors in that layer. Use request from the previous example to let TablePro own these states.

Run example

Run this example in a new tab

View the controlled pagination source
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
        }}
      />
    )
  },
})

Advanced search ​

Switch between local matching and a mock remote query. After each action, compare the draft, applied filters, transformed parameters, and actual list request.

  1. Combine filters. Submit multiple statuses and a creation date range. The remote query splits the dates into createdFrom and createdTo. Page changes reuse the parameters.
  2. Dependencies and cancellation. Switch quickly between North and South. The owner draft clears and the previous options request is canceled. Search South's options for Wang.
  3. Zero and boolean values. Apply the delivery and amount scenario and expand an order. Follow the product cascader, warehouse tree, delivery control, and datetime field. Confirm minAmount: 0 and invoiced: false are preserved.
  4. Validation and automatic apply. Submit a one-character keyword and check that existing rows remain. Correct it, enable automatic submission on input, and edit repeatedly to see the debounce.
  5. Recover independent failures. Fail the owner options or list request once. Retry options at the field, or resubmit the list query.
Run example

Run this example in a new tab

View the search example, business API, and demo fixtures
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)
  )
}

Automatic height and virtual scrolling ​

Enable Virtual rows, then show the footer and action slots. The list gives the new content room while the paginator stays below the rows. Open the example in a new tab and resize its height. Compare the available space with filters expanded and collapsed. Virtual scrolling reduces the rendered row count. The current page, loaded rows, and export scope are calculated as usual.

Run example

Run this example in a new tab

View the automatic height source
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>
    )
  },
})

Column settings and persistence ​

  1. Open Column settings. Hide Name and Email. The Contact details group disappears once both children are hidden.
  2. Drag root columns or use the move buttons. Columns with widths can be pinned to the start or end. Enable resizing, then drag a header edge.
  3. Click Reset column layout to restore initial order, pinning, and width settings while keeping visibility.
  4. Open the example in a new tab, hide a column, and reload that same tab. columnStateKey saves visibility in a separate session namespace. Production applications can include the tenant or account ID in the key.
  5. Toggle Include the ID field to change the column definitions. Data columns and groups use stable keys. Selection columns are outside visible data column settings.
Run example

Run this example in a new tab

View the column settings source
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>
    )
  },
})

Custom slots and row menu ​

Filter by email in the custom form, which submits through submit(values) from filters. Use the title actions to return to page 1 and set 20 rows per page. Select rows and clear them with the bottom action. Right-click a row to run a sample menu action. The callback receives the row's data.

Run example

Run this example in a new tab

View the custom slot source
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>
    )
  },
})

Copy an image ​

Click Copy table image in any full table above and paste it into an image-capable chat or document. Try hiding or pinning columns, or scrolling horizontally, before copying. Virtual scrolling captures only the content currently rendered in the visible table area. The copy action is on by default and can be hidden with showCopyImage={false}. Printing is off by default.

Printing and CSV ​

This example sets showPrint. Filter by name or hide a column in Column settings. Choose More actions → Print table to preview the current page's visible data columns. Print a separate summary previews a custom region supplied via print({ target }). Cancel the browser dialog to preview without printing.

Run example

Run this example in a new tab

View printing source and styles
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;
}

To compare both CSV scopes, download the files in Export, print, and the instance lifecycle.

Instance methods and hooks ​

Query, retry, and pagination ​

Go to page 2 and compare Refresh current page with Refresh from page 1. Simulate failure and observe queryState loading, failure, and totals, then refresh to recover. Submitting a name filter displays the actual request parameters. Change pages rapidly to see the latest request win.

Run example

Run this example in a new tab

View the query hook source
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>
    )
  },
})

Cross-page selection and bulk actions ​

Use Select current page on two pages, then Deselect current page. Only that page's keys are removed. Mark the remaining selected rows and return to the relevant page to check them. Sort rows, then use Clear sorting to see how the example calls the underlying method exposed by getTableInstance().

Run example

Run this example in a new tab

View the selection hook source
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>
    )
  },
})

Export, print, and the instance lifecycle ​

Download Export current page as CSV and Export all loaded rows as CSV, then compare the row counts. The latter uses keepOriginalData to export the entire supplied batch. In remote mode it does not fetch other pages. Click Unmount table to disable the actions, then mount it again to re-register the instance.

Run example

Run this example in a new tab

View the output hook source
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>
    )
  },
})

Back to the TablePro API reference