VuePress侧边栏配置与useSidebar的使用方式
作者:红衣大叔
这篇文章主要介绍了VuePress侧边栏配置与useSidebar的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
VuePress侧边栏配置与useSidebar的使用
在VuePress中,侧边栏(Sidebar)是一个重要的组成部分,用于组织文档结构,提供给用户方便的导航体验。
本文将详细介绍如何配置侧边栏,并介绍如何使用 useSidebar
组合式函数来操作侧边栏的状态。
单一侧边栏的配置
最简单的侧边栏配置方式是通过一个数组来定义导航结构。每个第一级的项目定义了一个“部分”(section),它应该包含一个文本标题(text)以及实际的导航链接(items)。
- 例如:
export default { themeConfig: { sidebar: [ { text: 'Section Title A', items: [ { text: 'Item A', link: '/item-a' }, { text: 'Item B', link: '/item-b' }, // 更多子项... ] }, { text: 'Section Title B', items: [ { text: 'Item C', link: '/item-c' }, { text: 'Item D', link: '/item-d' }, // 更多子项... ] } ] } }
每个链接应指定以 /
开头的实际文件路径。如果链接的末尾加上斜杠,则表示指向对应目录下的 index.md
文件。
多个侧边栏的配置
你可以根据页面路径来显示不同的侧边栏。例如,你可以为不同的文档部分配置单独的侧边栏。
- 首先按需组织Markdown文件:
. ├─ guide/ │ ├─ index.md │ ├─ one.md │ └─ two.md └─ config/ ├─ index.md ├─ three.md └─ four.md
- 然后更新配置文件以定义每个部分的侧边栏:
export default { themeConfig: { sidebar: { '/guide/': [ { text: 'Guide', items: [ { text: 'Index', link: '/guide/' }, { text: 'One', link: '/guide/one' }, { text: 'Two', link: '/guide/two' } ] } ], '/config/': [ { text: 'Config', items: [ { text: 'Index', link: '/config/' }, { text: 'Three', link: '/config/three' }, { text: 'Four', link: '/config/four' } ] } ] } } }
可折叠的侧边栏组
在侧边栏中添加可折叠的功能,可以让用户通过点击切换按钮来隐藏或显示某个部分的内容。这有助于在内容较多的情况下保持界面的整洁,并提供更好的用户体验。
要配置可折叠的侧边栏组,可以在定义侧边栏的配置中为每个部分添加一个 collapsed
属性。
- 例如:
export default { themeConfig: { sidebar: [ { text: 'Section Title A', collapsed: false, // 默认展开 items: [ { text: 'Item A', link: '/item-a' }, { text: 'Item B', link: '/item-b' }, // 更多子项... ] }, { text: 'Section Title B', collapsed: true, // 默认收起 items: [ { text: 'Item C', link: '/item-c' }, { text: 'Item D', link: '/item-d' }, // 更多子项... ] } ] } }
使用 useSidebar 组合式函数
useSidebar
是一个组合式函数,提供了与侧边栏相关数据的访问。它返回一个包含多个响应式引用(Ref)和一些实用函数的对象。
export interface DocSidebar { isOpen: Ref<boolean>, sidebar: ComputedRef<DefaultTheme.SidebarItem[]>, sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>, hasSidebar: ComputedRef<boolean>, hasAside: ComputedRef<boolean>, leftAside: ComputedRef<boolean>, isSidebarEnabled: ComputedRef<boolean>, open: () => void, close: () => void, toggle: () => void }
- 使用
useSidebar
的示例如下:
<script setup> import { useSidebar } from '@vuepress/theme-default'; const { hasSidebar } = useSidebar(); </script> <template> <div v-if="hasSidebar">仅在存在侧边栏时显示</div> </template>
通过这种方式,你可以更灵活地管理和控制侧边栏的行为,以增强用户体验并使页面布局更加动态和响应式。
总结
通过合理的侧边栏配置,可以显著提升文档的导航性和用户体验。无论是单一的侧边栏还是根据不同路径显示的多个侧边栏,VuePress 都提供了丰富的配置选项。同时,useSidebar
组合式函数进一步增强了侧边栏的交互性和动态性。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。