跳转到正文

应用组件与 Provider ​

这些组件按文件默认导入,例如 import AppPageHeader from '@/app-components/app/AppPageHeader'。它们依赖应用 Store、路由或 DOM,按默认 App 挂载顺序集成。

后台上下文示例 ​

这个预览运行后台的工作台和布局。在侧栏进入「模板 Hooks」,可以切换主题、水印、布局加载和菜单状态。版本提示、请求取消等 Provider 属于应用初始化流程,接入顺序见下表。

查看预览入口与工作台源码
tsx
import './styles/entry'
import AppNaiveGlobalProvider from '@/app-components/provider/AppNaiveGlobalProvider'
import AppStyleProvider from '@/app-components/provider/AppStyleProvider'
import AppWatermarkProvider from '@/app-components/provider/AppWatermarkProvider'
import { APP_THEME } from '@/app-config'
import { setupDayjs } from '@/dayjs'
import { setupDirectives } from '@/directives'
import { useI18n, useTheme } from '@/hooks'
import { setupI18n } from '@/locales'
import { registerApiMock } from '@/mocks/register'
import { router } from '@/router'
import {
  getStaticAppRoutes,
  setAppRouteModules,
} from '@/router/app-route-modules'
import { getSystemRoutes } from '@/router/routes'
import type { AppRouteRecordRaw } from '@/router/types'
import { expandRoutes } from '@/router/utils/expand-routes'
import { joinRoutePath } from '@/router/utils/join-route-path'
import { useSettingActions, useSettingGetters } from '@/store'
import { useMemoryCache } from '@/utils/cache-backend'
import { exampleFocusKey } from '@/views/demo/hooks/example-focus'
import type { IconPackage } from '@ray-template/icons'
import { iconSprites } from '@ray-template/icons/manifest'
import { provideUiServices } from '@ray-template/ui/services'
import { createStorage } from '@ray-template/utils/storage'
import { RouterView } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const examplePaths = new Set([
  '/dashboard',
  '/tables',
  '/form',
  '/modal-demo',
  '/echart',
  '/flow',
  '/segment',
  '/iframe',
  '/draggable-card',
  '/svg-icons',
  '/directive',
  '/template-hooks',
  '/web-hooks',
  '/multi',
  '/precision',
  '/cache-demo',
  '/axios',
  '/qrcode',
])

function selectExampleRoutes(
  routes: AppRouteRecordRaw[],
  parentPath = '',
): AppRouteRecordRaw[] {
  return routes.flatMap((route) => {
    const path = joinRoutePath(parentPath, route.path)

    if (examplePaths.has(path)) return [route]

    const children = selectExampleRoutes(route.children ?? [], path)

    return children.length ? [{ ...route, children }] : []
  })
}

const params = new URLSearchParams(location.search)
const withLayout = params.get('layout') === '1'
const examples = [
  ...selectExampleRoutes(getStaticAppRoutes()),
  {
    path: '/docs-core-utils',
    name: 'DocsCoreUtils',
    component: () => import('@/views/demo/docs-core-utils'),
    meta: { i18nKey: 'menu.DocsCoreUtils', order: 8 },
  },
  {
    path: '/docs-browser-utils',
    name: 'DocsBrowserUtils',
    component: () => import('@/views/demo/docs-browser-utils'),
    meta: { i18nKey: 'menu.DocsBrowserUtils', order: 9 },
  },
  {
    path: '/docs-storage-utils',
    name: 'DocsStorageUtils',
    component: () => import('@/views/demo/docs-storage-utils'),
    meta: { i18nKey: 'menu.DocsStorageUtils', order: 10 },
  },
]

const DocumentationExample = defineComponent({
  name: 'DocumentationExample',
  setup() {
    const { t } = useI18n()
    const { getAppTheme, getLocaleLanguage, getThemeStyle } =
      useSettingGetters()

    provideUiServices({
      dark: () => getAppTheme.value,
      locale: () => getLocaleLanguage.value,
      chartTheme: () => APP_THEME.echartTheme ?? `ray-${getThemeStyle.value}`,
      translate: t,
      iconUrl: (name, prefix) =>
        `${iconSprites[name.split('/')[0] as IconPackage]}#${prefix}-${name}`,
      columnStorage: createStorage(window.sessionStorage, 'ray-doc-examples'),
      reportError: (message) => window.$message?.error(message),
      reportSuccess: (message) => window.$message?.success(message),
    })

    return () => (
      <AppNaiveGlobalProvider>
        <AppStyleProvider />
        <AppWatermarkProvider />
        <RouterView />
      </AppNaiveGlobalProvider>
    )
  },
})

async function mountExample() {
  useMemoryCache()
  registerApiMock()

  const app = createApp(DocumentationExample)

  app.use(createPinia())
  setupI18n(app)
  setupDayjs()
  setupDirectives(app)

  const { updateLocale } = app.runWithContext(useSettingActions)
  const { darkTheme, lightTheme } = app.runWithContext(useTheme)

  updateLocale(params.get('lang') === 'en' ? 'en-US' : 'zh-CN')

  if (params.get('theme') === 'dark') darkTheme()
  else lightTheme()

  setAppRouteModules(examples)

  const routes = [
    ...expandRoutes(examples),
    ...getSystemRoutes(),
  ] as unknown as RouteRecordRaw[]

  if (withLayout) {
    router.addRoute({
      path: '/',
      component: () => import('@/layout'),
      children: routes,
    })
  } else {
    for (const route of routes) router.addRoute(route)
  }

  app.use(router)
  await router.isReady()

  const focus = params.get('focus')

  if (focus) {
    app.provide(exampleFocusKey, {
      path: router.currentRoute.value.path,
      names: new Set(focus.split(',')),
    })
  }

  app.mount('#app')
}

void mountExample()
tsx
import './index.scss'
import AppPageHeader from '@/app-components/app/AppPageHeader'
import AppShareLink from '@/app-components/app/AppShareLink'
import { useI18n } from '@/hooks'
import { useMenuGetters } from '@/store'
import type { AppMenuOption } from '@/types'
import { RIcon } from '@ray-template/ui/icon'
import { NCard, NDescriptions, NDescriptionsItem } from 'naive-ui'
import { RouterLink } from 'vue-router'

export default defineComponent({
  name: 'RDashboard',
  setup() {
    const { t } = useI18n('dashboard')
    const text = (key: string) => t<string>(key)
    const { getMenuOptions } = useMenuGetters()
    const shortcutsTitle = useId()
    const { dependencies, devDependencies } = __APP_CFG__.pkg
    const stack = [
      { name: 'Vue', version: dependencies.vue, detail: 'Composition API' },
      { name: 'Vite', version: devDependencies.vite, detail: 'Rolldown' },
      {
        name: 'TypeScript',
        version: devDependencies.typescript,
        detail: 'TSX',
      },
      {
        name: 'Pinia',
        version: dependencies.pinia,
        detail: text('stateManagement'),
      },
    ]
    const destinations = [
      {
        path: '/template-hooks',
        icon: 'action/setting',
        title: 'hooks',
        description: 'hooksDescription',
      },
      {
        path: '/layout-demo',
        icon: 'navigation/layout',
        title: 'layout',
        description: 'layoutDescription',
      },
      {
        path: '/svg-icons',
        icon: 'navigation/icons',
        title: 'icons',
        description: 'iconsDescription',
      },
    ] as const
    const shortcuts = computed(() => {
      const visiblePaths = new Set<string>()
      const collect = (menus: AppMenuOption[]) => {
        for (const menu of menus) {
          // 菜单树已经按角色过滤;隐藏任一祖先时,整条分支都不能成为快捷入口。
          if (menu.show === false) continue

          if (!menu.meta.windowOpen) visiblePaths.add(menu.fullPath)

          if (menu.children?.length) collect(menu.children)
        }
      }

      collect(getMenuOptions.value)

      return destinations.filter(({ path }) => visiblePaths.has(path))
    })

    return () => (
      <section class="r-dashboard">
        <AppPageHeader
          class="r-dashboard__header"
          title={text('title')}
          description={text('description')}
          eyebrow="RAY TEMPLATE / WORKSPACE"
        >
          <span class="r-dashboard__brand">
            <RIcon name="logo/ray" size={44} />
          </span>
        </AppPageHeader>
        <div class="r-dashboard-stack">
          {stack.map((item) => (
            <article key={item.name} class="r-dashboard-stack__item">
              <span>{item.name}</span>
              <strong>{item.version}</strong>
              <small>
                {item.name === 'Pinia' ? text('stateManagement') : item.detail}
              </small>
            </article>
          ))}
        </div>
        {shortcuts.value.length ? (
          <section aria-labelledby={shortcutsTitle}>
            <h2 id={shortcutsTitle} class="r-dashboard__section-title">
              {text('explore')}
            </h2>
            <nav class="r-dashboard-shortcuts" aria-labelledby={shortcutsTitle}>
              {shortcuts.value.map((item) => (
                <RouterLink
                  key={item.path}
                  to={item.path}
                  class="r-dashboard-shortcut"
                >
                  <span class="r-dashboard-shortcut__icon" aria-hidden="true">
                    <RIcon name={item.icon} size={20} />
                  </span>
                  <span class="r-dashboard-shortcut__copy">
                    <strong>{text(item.title)}</strong>
                    <small>{text(item.description)}</small>
                  </span>
                  <RIcon
                    class="r-dashboard-shortcut__arrow"
                    name="directional/right_arrow"
                    size={14}
                  />
                </RouterLink>
              ))}
            </nav>
          </section>
        ) : null}
        <div class="r-dashboard-info">
          <NCard title={text('project')}>
            <p class="r-dashboard-info__intro">{text('projectDescription')}</p>
            <div class="r-dashboard-features">
              <span>Vue 3 + TSX</span>
              <span>Naive UI</span>
              <span>{text('routing')}</span>
              <span>{text('themeAndLocale')}</span>
            </div>
            <p class="r-dashboard-info__feedback">
              {text('feedbackBefore')}{' '}
              <a
                href="https://github.com/XiaoDaiGua-Ray/ray-template/issues"
                target="_blank"
                rel="noreferrer"
              >
                GitHub Issues <RIcon name="action/external-link" size={12} />
              </a>
              {text('feedbackAfter')}
            </p>
          </NCard>
          <NCard title={text('author')}>
            <NDescriptions
              column={1}
              labelPlacement="left"
              labelStyle={{ width: '92px' }}
            >
              <NDescriptionsItem label={text('frameworks')}>
                Vue3.x / React
              </NDescriptionsItem>
              <NDescriptionsItem label={text('experience')}>
                {text('experienceValue')}
              </NDescriptionsItem>
              <NDescriptionsItem label={text('bio')}>
                {text('bioValue')}
              </NDescriptionsItem>
            </NDescriptions>
          </NCard>
        </div>
        <NCard title={text('linksTitle')}>
          <AppShareLink variant="cards" />
        </NCard>
      </section>
    )
  },
})

页面组件 ​

组件配置和注意事项
AppPageHeadertitle 必填,description 默认空,eyebrow 默认 RAY TEMPLATE。默认插槽是右侧操作区,页面内容放在组件之外。
AppShareLinkvariant: 'compact' | 'cards',默认 compact,从 dashboard 语言包读文案。链接由组件内配置,不接收任意链接列表。
AppAvatar从 Signing Store 读头像与名字。avatarSize、spaceSize 默认 medium,vertical 默认 false;头像使用圆形、cover,空头像用名称首字。src 和 size 会被内部读取的值覆盖。
AppGlobalSpin接收 NSpin 属性与插槽。显隐以 Runtime Store 的 globalSpinning 为准,传入 show 会被覆盖;和布局内容区 Spin 独立。
AppLockScreen由 setting.lockScreenSwitch 控制锁屏设置弹窗,不允许点遮罩或 Esc 关闭。锁定后由布局读取 Lock Screen Store 呈现解锁界面。
tsx
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { NButton } from 'naive-ui'

export const renderOrdersHeader = (create: () => void) => (
  <AppPageHeader eyebrow="库存" title="订单" description="查看和维护销售订单">
    <NButton type="primary" onClick={create}>
      新建订单
    </NButton>
  </AppPageHeader>
)

Provider ​

Provider职责与调用时机
AppNaiveGlobalProvider包裹默认插槽并同步明暗、主题覆盖、UI locale 和日期 locale。提供 Message、Dialog、Modal、Notification、LoadingBar 等上下文,并建立 window.$message、$dialog、$notification、$loadingBar。离散 API 在 Provider 初始化后可用,卸载时释放;不要在模块顶层提前调用。
AppStyleProvider同步 HTML 明暗类、CSS 主色和窗口尺寸变量,结束首屏加载动画。应用主题应通过设置方法更新。
AppVersionProvider启动时比较构建版本与本地版本。第一次写入缓存,变化时提示,确认会走退出并刷新;取消关闭提示。
AppWatermarkProvider按设置渲染全屏 Naive UI 水印;独立页面如需局部水印可自行在目标区域使用 NWatermark。
AppRequestCancelerProvider默认布局内容的路由更新钩子会取消模板管理的请求。替换内容插槽时,根据实际导航方式保留取消行为。

应用组件说明 · 布局配置 · Store · 请求取消