執行時期 API
VitePress 提供多個內建 API,讓您可以存取應用程式資料。VitePress 也附帶幾個內建元件,可以在全域使用。
協助函式方法可以從 vitepress
全域匯入,通常用於自訂佈景主題的 Vue 元件。不過,它們也可以在 .md
頁面中使用,因為 markdown 檔案會編譯成 Vue 單一檔案元件。
以 use*
開頭的方法表示它是 Vue 3 組合 API 函式(「可組合」),只能在 setup()
或 <script setup>
中使用。
useData
可組合
傳回特定頁面的資料。傳回的物件具有下列類型
ts
interface VitePressData<T = any> {
/**
* Site-level metadata
*/
site: Ref<SiteData<T>>
/**
* themeConfig from .vitepress/config.js
*/
theme: Ref<T>
/**
* Page-level metadata
*/
page: Ref<PageData>
/**
* Page frontmatter
*/
frontmatter: Ref<PageData['frontmatter']>
/**
* Dynamic route params
*/
params: Ref<PageData['params']>
title: Ref<string>
description: Ref<string>
lang: Ref<string>
isDark: Ref<boolean>
dir: Ref<string>
localeIndex: Ref<string>
/**
* Current location hash
*/
hash: Ref<string>
}
interface PageData {
title: string
titleTemplate?: string | boolean
description: string
relativePath: string
filePath: string,
headers: Header[]
frontmatter: Record<string, any>
params?: Record<string, any>
isNotFound?: boolean
lastUpdated?: number
}
範例
vue
<script setup>
import { useData } from 'vitepress'
const { theme } = useData()
</script>
<template>
<h1>{{ theme.footer.copyright }}</h1>
</template>
useRoute
可組合
傳回目前的路由物件,類型如下
ts
interface Route {
path: string
data: PageData
component: Component | null
}
useRouter
可組合
傳回 VitePress 路由執行個體,讓您可以透過程式導覽至其他頁面。
ts
interface Router {
/**
* Current route.
*/
route: Route
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
/**
* Called before the page component is loaded (after the history state is
* updated). Return `false` to cancel the navigation.
*/
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
/**
* Called after the route changes.
*/
onAfterRouteChanged?: (to: string) => Awaitable<void>
}
withBase
協助函式
- 類型:
(path: string) => string
將設定好的 base
附加到指定的 URL 路徑。另請參閱 基本 URL。
<Content />
元件
<Content />
元件會顯示已轉譯的 markdown 內容。在 建立自訂佈景主題 時很有用。
vue
<template>
<h1>Custom Layout!</h1>
<Content />
</template>
<ClientOnly />
元件
<ClientOnly />
元件只會在用戶端轉譯其插槽。
由於 VitePress 應用程式會在產生靜態建置時以 Node.js 在伺服器端轉譯,因此任何 Vue 使用都必須符合通用程式碼需求。簡而言之,請確定只在 beforeMount 或 mounted 鉤子中存取瀏覽器/DOM API。
如果您正在使用或展示不友善於伺服器端轉譯的元件(例如,包含自訂指令),您可以將它們包覆在 ClientOnly
元件中。
範本
<ClientOnly>
<NonSSRFriendlyComponent />
</ClientOnly>
- 相關:SSR 相容性
$frontmatter
範本全域
在 Vue 表達式中直接存取當前頁面的 frontmatter 資料。
md
---
title: Hello
---
# {{ $frontmatter.title }}
$params
範本全域
在 Vue 表達式中直接存取當前頁面的 動態路由參數。
md
- package name: {{ $params.pkg }}
- version: {{ $params.version }}