Skip to content
ReferenceVersion 6.0.2

App Components and Providers ​

Use default imports by file, for example import AppPageHeader from '@/app-components/app/AppPageHeader'. These components depend on application stores, routing, or the DOM. Integrate them in the default App mount order.

Admin context example ​

This preview runs the admin dashboard and layout. Use the Template Hooks entry in the sidebar to change the theme, watermark, layout loading state, and menu state. Version prompts, request cancellation, and other providers belong to application initialization.

View the preview entry point and dashboard source
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>
    )
  },
})

Page components ​

ComponentConfiguration and behavior
AppPageHeadertitle is required. description defaults to empty, and eyebrow defaults to RAY TEMPLATE. Place action buttons in the default slot on the right and page content outside the component.
AppShareLinkvariant: 'compact' | 'cards' defaults to compact. Text comes from the dashboard messages. The component defines its own links.
AppAvatarReads avatar and name from Signing Store. avatarSize and spaceSize default to medium, and vertical defaults to false. Avatars are round and use cover sizing. The first character of the name is the fallback. Internally derived src and size take precedence.
AppGlobalSpinAccepts NSpin props and slots. Runtime Store's globalSpinning controls visibility and overrides show. The layout content spinner is independent.
AppLockScreensetting.lockScreenSwitch controls the setup dialog. The dialog stays open on backdrop clicks and Esc. After locking, the layout reads Lock Screen Store to render the unlock screen.
tsx
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { NButton } from 'naive-ui'

export const renderOrdersHeader = (create: () => void) => (
  <AppPageHeader
    eyebrow="Inventory"
    title="Orders"
    description="View and manage sales orders"
  >
    <NButton type="primary" onClick={create}>
      New order
    </NButton>
  </AppPageHeader>
)

Providers ​

ProviderResponsibilities and lifecycle
AppNaiveGlobalProviderWraps the default slot and syncs color mode, theme overrides, UI locale, and date locale. Provides Message, Dialog, Modal, Notification, and LoadingBar contexts and assigns window.$message, $dialog, $notification, and $loadingBar. Discrete APIs are available after initialization and released on unmount. Call them after the provider is ready.
AppStyleProviderSyncs HTML color-mode classes, CSS primary color, and viewport variables, and ends the startup animation. Use settings actions to change the theme.
AppVersionProviderCompares the built version with the cached version at startup. The first startup writes the version. On version change, confirming the prompt signs out and reloads, and canceling closes the prompt.
AppWatermarkProviderRenders a full-page Naive UI watermark from preferences. Standalone pages can place NWatermark in a local region.
AppRequestCancelerProviderCancels template-managed requests from the route update hook in the default content area. Preserve cancellation as needed when replacing the content slot.

App components · Layout settings · Stores · Request cancellation