VitePress运行时API详解
本文将详细介绍VitePress提供的运行时API,这些API可以帮助我们更好地控制页面行为和获取站点数据。
useData() API
useData() 是VitePress提供的主要运行时API,可用于访问当前页面的站点、主题和页面数据。它在 .md 和 .vue 文件中都能正常工作:
md
<script setup>
import { useData } from 'vitepress'
const { theme, page, frontmatter } = useData()
</script>
## 结果
### 主题数据
<pre>{{ theme }}</pre>
### 页面数据
<pre>{{ page }}</pre>
### 页面Frontmatter
<pre>{{ frontmatter }}</pre>实际结果
主题数据
{
"search": {
"provider": "local",
"options": {}
},
"outline": {
"level": [
1,
6
],
"label": "目录"
},
"nav": [
{
"text": "首页",
"link": "/"
},
{
"text": "博客",
"link": "/posts/"
},
{
"text": "关于",
"link": "/about"
}
],
"sidebar": {
"/posts/": [
{
"text": "前端",
"collapsed": false,
"items": [
{
"text": "在win11开发兼容ie的网页",
"link": "/posts/frontend/develop-ie-win11/develop-ie-win11"
},
{
"text": "最近开发时遇到的问题(var和async)",
"link": "/posts/frontend/problem-for-var-and-async/problem-for-var-and-async"
}
]
},
{
"text": "总结",
"collapsed": true,
"items": [
{
"text": "2025总结.md",
"link": "/posts/summary/2025总结.md"
}
]
},
{
"text": "vitepress示例",
"collapsed": true,
"items": [
{
"text": "给文章添加tag并支持搜索索引",
"link": "/posts/vitepress/article-tag"
},
{
"text": "我的第一篇博客",
"link": "/posts/vitepress/my-first-post"
},
{
"text": "VitePress使用技巧",
"link": "/posts/vitepress/vitepress-tips"
},
{
"text": "VitePress中的Markdown扩展功能",
"link": "/posts/vitepress/markdown-extensions"
},
{
"text": "VitePress运行时API详解",
"link": "/posts/vitepress/runtime-api-examples"
}
]
}
]
},
"socialLinks": [
{
"icon": "github",
"link": "https://github.com/mqnu00"
},
{
"icon": "rss",
"link": "/blog/rss.xml"
}
],
"footer": {
"message": "Released under the MIT License.",
"copyright": "Copyright © 2025-present 广习习"
}
}页面数据
{
"title": "VitePress运行时API详解",
"description": "",
"frontmatter": {
"title": "VitePress运行时API详解",
"date": "2025-01-18T00:00:00.000Z",
"author": "广习习",
"tags": [
"技术分享",
"VitePress",
"API"
],
"outline": "deep"
},
"headers": [],
"relativePath": "posts/vitepress/runtime-api-examples.md",
"filePath": "posts/vitepress/runtime-api-examples.md",
"git": {
"updated": "2025-11-27T02:20:16Z",
"history": [
{
"sha": "730a7d117141f9fc9106caec61861070e057affd",
"author": "mqnu00",
"date": "2025-11-27T02:20:16Z",
"message": "refactor: 配置文章结构",
"url": "https://github.com/mqnu00/blog/commit/730a7d117141f9fc9106caec61861070e057affd"
}
]
}
}页面Frontmatter
{
"title": "VitePress运行时API详解",
"date": "2025-01-18T00:00:00.000Z",
"author": "广习习",
"tags": [
"技术分享",
"VitePress",
"API"
],
"outline": "deep"
}应用场景
useData() API可以用于:
- 根据站点配置动态渲染内容
- 访问页面级的元数据
- 在自定义组件中访问VitePress的内部数据
更多运行时API的详细信息,请查看 官方文档。