import{_ as n}from"./chunks/AdminExample.vue_vue_type_script_setup_true_lang.wPcM-fsm.js";import{o as h,c as k,j as i,a,E as l,a3 as t}from"./chunks/framework.D8G7yXPy.js";const d=JSON.parse('{"title":"分页与右键菜单","description":"","frontmatter":{},"headers":[],"relativePath":"reference/hooks/interaction.md","filePath":"reference/hooks/interaction.md"}'),p={name:"reference/hooks/interaction.md"},y=Object.assign(p,{setup(E){return(e,s)=>(h(),k("div",null,[s[0]||(s[0]=i("h1",{id:"分页与右键菜单",tabindex:"-1"},[a("分页与右键菜单 "),i("a",{class:"header-anchor",href:"#分页与右键菜单","aria-label":'Permalink to "分页与右键菜单"'},"​")],-1)),s[1]||(s[1]=i("h2",{id:"交互示例",tabindex:"-1"},[a("交互示例 "),i("a",{class:"header-anchor",href:"#交互示例","aria-label":'Permalink to "交互示例"'},"​")],-1)),l(n,{path:"/web-hooks",title:"分页和右键菜单",focus:"usePagination,useContextmenuCoordinate"}),s[2]||(s[2]=t(`
查看示例源码
tsx
import {
  useContextmenuCoordinate,
  useDayjs,
  useDevice,
  useDomToImage,
  useElementFullscreen,
  useI18n,
  usePagination,
  usePrint,
  useVueRouter,
} from '@/hooks'
import { useSettingActions } from '@/store'
import {
  NAlert,
  NButton,
  NDropdown,
  NFlex,
  NInput,
  NPagination,
  NTag,
  useThemeVars,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import HookExample from './HookExample'

export default defineComponent({
  name: 'WebHooks',
  setup() {
    const { t } = useI18n('hooks')
    const text = (key: string) => t<string>(key)
    const { t: showcaseT } = useI18n('showcase')
    const label = (key: string) => showcaseT<string>(key)
    const themeVars = useThemeVars()
    const device = useDevice()
    const dayjs = useDayjs()
    const { router } = useVueRouter()
    const { updateLocale: changeLocale } = useSettingActions()
    const [pagination, pages] = usePagination(void 0, {
      itemCount: 95,
      pageSize: 10,
    })
    const date = ref('2026-11-03')
    const dayRange = ref(dayjs.getStartAndEndOfDay())
    const target = ref<HTMLElement>()
    const fullscreen = useElementFullscreen(target)
    const capture = useDomToImage(target, { imageType: 'png', cacheBust: true })
    const printer = usePrint(target, { type: 'html', targetStyles: ['*'] })
    const image = ref('')
    const error = ref('')
    const busy = ref(false)
    const contextTarget = ref<HTMLElement>()
    const context = useContextmenuCoordinate(contextTarget)
    const contextStopped = ref(false)
    const selected = ref('')
    const rows = computed(() => {
      const start = (pages.getPage() - 1) * pages.getPageSize()

      return Array.from(
        {
          length: Math.min(
            pages.getPageSize(),
            Math.max(0, pages.getItemCount() - start),
          ),
        },
        (_, index) => start + index + 1,
      )
    })
    const createImage = async () => {
      busy.value = true
      error.value = ''

      try {
        image.value = await capture.create()
      } catch (cause) {
        error.value = cause instanceof Error ? cause.message : String(cause)
      } finally {
        busy.value = false
      }
    }
    const example = (
      name: string,
      code: string,
      children: () => JSX.Element,
    ) => (
      <HookExample
        name={name}
        description={text(\`descriptions.\${name}\`)}
        code={code}
      >
        {children()}
      </HookExample>
    )

    return () => (
      <DemoPage
        title={label('webTitle')}
        description={text('webIntro')}
        eyebrow={label('webEyebrow')}
        meta="9 Hooks"
      >
        <h2 class="r-demo-section-heading">{label('commonUtilities')}</h2>
        <div class="r-hook-grid">
          {example(
            'useDevice',
            \`const { width, height, isTabletOrSmaller } = useDevice({ media: 768 })\\n// Refs update when the viewport changes; listeners are released with the scope.\`,
            () => (
              <NFlex>
                <NTag>
                  {device.width.value} × {device.height.value}
                </NTag>
                <NTag>
                  {device.isTabletOrSmaller.value
                    ? text('smallScreen')
                    : text('desktop')}
                </NTag>
              </NFlex>
            ),
          )}
          {example(
            'usePagination',
            \`const [pagination, { getPage, setPage, setPageSize, resetPagination }] = usePagination(loadRows, { itemCount: 95 })\\n<NPagination {...pagination.value} />\\n// Changing page size resets the page to 1.\`,
            () => (
              <NFlex vertical>
                <NFlex>
                  {rows.value.map((row) => (
                    <NTag key={row}>#{row}</NTag>
                  ))}
                </NFlex>
                <div style="overflow-x: auto">
                  <NPagination {...pagination.value} />
                </div>
                <NFlex>
                  <NButton onClick={() => pages.setPage(2)}>
                    {text('pageTwo')}
                  </NButton>
                  <NButton onClick={() => pages.setPageSize(20)}>
                    {text('pageSize20')}
                  </NButton>
                  <NButton onClick={pages.resetPagination}>
                    {text('reset')}
                  </NButton>
                </NFlex>
              </NFlex>
            ),
          )}
          {example(
            'useDayjs',
            \`const { format, daysDiff, isDateInRange, getStartAndEndOfDay, isDayjs, locale } = useDayjs()\\nformat('2026-11-03', { format: 'YYYY/MM/DD' })\\ndaysDiff('2026-11-01', '2026-11-03')\\nisDateInRange('2026-11-03', { start: '2026-11-01', end: '2026-11-30' })\`,
            () => (
              <NFlex vertical>
                <NInput
                  value={date.value}
                  onUpdateValue={(value) => {
                    date.value = value
                  }}
                  aria-label={text('date')}
                />
                <pre class="r-demo-code">
                  <code>
                    {JSON.stringify(
                      {
                        format: dayjs.format(date.value),
                        daysDiff: dayjs.daysDiff('2026-11-01', date.value),
                        inRange: dayjs.isDateInRange(date.value, {
                          start: '2026-11-01',
                          end: '2026-11-30',
                        }),
                        startOfDay: dayRange.value.formatStartOfDay,
                        endOfDay: dayRange.value.formatEndOfDay,
                      },
                      null,
                      2,
                    )}
                  </code>
                </pre>
                <NButton
                  onClick={() => {
                    dayRange.value = dayjs.getStartAndEndOfDay()
                  }}
                >
                  {text('refreshDate')}
                </NButton>
              </NFlex>
            ),
          )}
          {example(
            'useI18n',
            \`const { t } = useI18n('hooks')\\nt('webIntro')\\nt('hooks.webIntro')\\nconst { updateLocale } = useSettingActions()\\nupdateLocale('en-US')\`,
            () => (
              <NFlex vertical>
                <span>{text('webIntro')}</span>
                <NFlex>
                  <NButton onClick={() => changeLocale('zh-CN')}>
                    简体中文
                  </NButton>
                  <NButton onClick={() => changeLocale('en-US')}>
                    English
                  </NButton>
                </NFlex>
              </NFlex>
            ),
          )}
          {example(
            'useVueRouter',
            \`const { router } = useVueRouter()\\nrouter.currentRoute.value.fullPath\\nrouter.replace({ path: '/web-hooks', query: { example: 'router' } })\`,
            () => (
              <NFlex vertical>
                <code style="overflow-wrap: anywhere">
                  {router.currentRoute.value.fullPath}
                </code>
                <NFlex>
                  <NButton
                    onClick={() =>
                      router.replace({
                        path: '/web-hooks',
                        query: { example: 'router' },
                      })
                    }
                  >
                    {text('updateQuery')}
                  </NButton>
                  <NButton onClick={() => router.push('/template-hooks')}>
                    {text('openTemplate')}
                  </NButton>
                </NFlex>
              </NFlex>
            ),
          )}
        </div>
        <h2 class="r-demo-section-heading">{label('browserCapabilities')}</h2>
        <div
          ref={target}
          class="r-hook-capture-target"
          style={{ backgroundColor: themeVars.value.cardColor }}
        >
          <h2>Ray Template</h2>
          <p>{text('captureTarget')}</p>
          <p class="r-hook-capture-target__stack">
            Vue 3 · TypeScript · Naive UI
          </p>
          {fullscreen.isFullscreen.value ? (
            <NButton onClick={fullscreen.exit}>
              {text('exitFullscreen')}
            </NButton>
          ) : null}
        </div>
        <div class="r-hook-grid">
          {example(
            'useElementFullscreen',
            \`const target = ref<HTMLElement>()\\nconst { enter, exit, toggleFullscreen, isFullscreen } = useElementFullscreen(target)\\n// CSS fullscreen: no browser permission required.\\n<div ref={target} />\`,
            () => (
              <NFlex align="center">
                <NTag>{String(fullscreen.isFullscreen.value)}</NTag>
                <NButton onClick={fullscreen.toggleFullscreen}>
                  {text('toggleElementFullscreen')}
                </NButton>
              </NFlex>
            ),
          )}
          {example(
            'useDomToImage',
            \`const { create } = useDomToImage(target, { imageType: 'png' })\\nconst png: string = await create()\\nconst blob: Blob | null = await create('blob')\`,
            () => (
              <NFlex vertical>
                <NButton loading={busy.value} onClick={createImage}>
                  {text('capture')}
                </NButton>
                {error.value ? (
                  <NAlert type="error">{error.value}</NAlert>
                ) : null}
                {image.value ? (
                  <img
                    src={image.value}
                    alt={text('capturePreview')}
                    style="max-width: 100%; height: auto"
                  />
                ) : null}
              </NFlex>
            ),
          )}
          {example(
            'usePrint',
            \`const target = ref<HTMLElement>()\\nconst { print } = usePrint(target, { type: 'html', targetStyles: ['*'] })\\n// Call from a button click.\`,
            () => (
              <NButton onClick={printer.print}>{text('print')}</NButton>
            ),
          )}
          {example(
            'useContextmenuCoordinate',
            \`const { x, y, show, updateShow, stop } = useContextmenuCoordinate(target)\\n<NDropdown show={show.value} x={x.value} y={y.value} trigger="manual" />\\nstop() // Hides the menu and removes all listeners.\`,
            () => (
              <NFlex vertical>
                <div
                  ref={contextTarget}
                  tabindex={0}
                  style="padding: 32px; border: 1px dashed var(--n-border-color)"
                  onKeydown={(event) => {
                    if (event.key === 'Escape') context.updateShow(false)
                  }}
                >
                  {text('rightClick')}
                </div>
                <code>
                  x: {context.x.value}, y: {context.y.value}, show:{' '}
                  {String(context.show.value)} {selected.value}
                </code>
                <NButton
                  disabled={contextStopped.value}
                  onClick={() => {
                    context.stop()
                    contextStopped.value = true
                  }}
                >
                  {contextStopped.value ? text('stopped') : text('stop')}
                </NButton>
                <NDropdown
                  show={context.show.value}
                  x={context.x.value}
                  y={context.y.value}
                  trigger="manual"
                  placement="bottom-start"
                  options={[
                    { key: 'copy', label: text('contextCopy') },
                    { key: 'inspect', label: text('contextInspect') },
                  ]}
                  onSelect={(key) => {
                    selected.value = String(key)
                    context.updateShow(false)
                  }}
                  onClickoutside={() => context.updateShow(false)}
                />
              </NFlex>
            ),
          )}
        </div>
      </DemoPage>
    )
  },
})

usePagination ​

usePagination(callback?, options?) 返回只读元组 [pagination, actions]。pagination 是可传给 NPagination 或 NDataTable 的响应式配置。缺省页码 1、每页 10 条、开启页大小选择器,候选 [10, 20, 50, 100]。options 接受除主题和原更新回调之外的 Pagination props,另提供 pageChange(page)、pageSizeChange(size)。

方法行为
getPage() / setPage(page)读取页码,或更新页码并通知。
getPageSize() / setPageSize(size)更新每页条数后先回到第 1 页,再通知。
getItemCount() / setItemCount(count)读取或写入条数,无值时读取为 0;写条数不触发请求回调。
getPagination()读取当前配置对象。
getCallback() / setCallback(callback?)读取、替换或移除通用回调。
resetPagination()页码回到 1,每页条数取第一个 pageSizes 的数字或对象 value,没有候选则用 10。

页码和页大小更新先改状态,再调用通用 callback,然后通知对应事件。重置读取当前 pagination.value.pageSizes,同时调用两个专用事件;各实例的默认候选数组彼此独立。远端查询建议只在通用回调发请求,避免两次加载。Hook 不会自动请求或裁剪数据,初始加载由页面负责。RTablePro 的 request 已管理分页,通常无需再套一层本 Hook。

ts
import { usePagination } from '@/hooks'

export function useOrdersPagination(
  load: (page: number, size: number) => void,
) {
  const [pagination, actions] = usePagination(
    () => load(actions.getPage(), actions.getPageSize()),
    { pageSizes: [10, 20, 50], itemCount: 0 },
  )
  return { pagination, actions, loadFirstPage: () => actions.setPage(1) }
}

useContextmenuCoordinate ​

useContextmenuCoordinate(target, options?) 接收元素、ref 或 getter。options 可以是捕获布尔值、事件监听选项(含 clickOutside(event)),或这些值的 ref / getter。内部强制使用 passive: false,防止浏览器原生菜单和自定义菜单同时打开。

返回只读 x、y(视口坐标)、show 和 updateShow(value)、stop()。右键发生后,先关闭旧菜单,再在下一次 Vue 更新写入坐标并打开。普通点击、外部点击会关闭菜单;外部点击回调在关闭后执行。菜单项选择后调用 updateShow(false)。stop() 停止所有监听并阻止尚未执行的打开操作,作用域销毁时也会清理。

tsx
import { useContextmenuCoordinate } from '@/hooks'
import { NDropdown } from 'naive-ui'
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup() {
    const area = ref<HTMLElement>()
    const { x, y, show, updateShow } = useContextmenuCoordinate(area)
    return () => (
      <div ref={area}>
        在这里点击鼠标右键
        <NDropdown
          trigger="manual"
          x={x.value}
          y={y.value}
          show={show.value}
          options={[{ key: 'details', label: '详情' }]}
          onSelect={() => updateShow(false)}
          onClickoutside={() => updateShow(false)}
        />
      </div>
    )
  },
})

源码:usePagination · useContextmenuCoordinate

`,11))]))}});export{d as __pageData,y as default};