VuePress 配置中的 Front-matter 默认值

Ban*_*nio 1 configuration static-site yaml-front-matter vuepress

我正在尝试将我的文档站点从 GitBook 切换到 Vuepress,但遇到了 front-matter 变量。在 GitBook 中,您只需在配置中添加变量,然后在页面上的任何位置使用它们作为{{ book.variable_name }}. 乍一看,在 Vuepress 中,事情似乎更加棘手。

我需要配置在整个站点中使用的几个变量,因此将它们添加到每个页面将是一场彻底的噩梦。该文档没有说明如何配置 front-matter 变量,但有一个 Jekyll 站点的链接。在 Jekyll 网站上,我发现这篇文章正是我想要实现的目标。问题是我不知道如何在配置中使用这些信息。

非常感谢任何帮助。我在官方仓库中问了这个问题,但这没有帮助。

小智 5

要定义一些可以在站点中的任何位置访问的变量,您可以将它们添加到主题配置中。

如果您还没有,请config.js在 处创建一个文件.vuepress/config.js

该文件应该导出一个对象。

themeConfig: {}您想为此添加一个。

您在该对象上设置的属性themeConfig将在您的整个站点上可用$themeConfig

//- .vuepress/config.js

module.exports = {
  themeConfig: {
    //- Define your variables here
    author: 'Name',
    foo: 'bar'
  }
}
Run Code Online (Sandbox Code Playgroud)
  {{ $themeConfig.author }} //- 'Name'
  {{ $themeConfig.foo }} //- 'bar
Run Code Online (Sandbox Code Playgroud)

您还可以通过使用全局计算函数,轻松地在本地/每页覆盖这一点。(这也可以提供一种更干净的方式来访问变量)

enhanceApp.js在与 相同的位置添加一个文件config.js,将使您能够访问 Vue 实例 - 您可以在其中为所有组件定义一个 mixin。

您可以在此 mixin 中定义一些计算属性,这些属性首先检查页面 frontmatter 数据中的值,然后回退到 themeConfig 中设置的值。允许您设置一些可以在每个页面本地覆盖的默认值。

//- .vuepress/enhanceApp.js

export default ({ Vue }) => {
  Vue.mixin({
    computed: {
      author() {
        const { $themeConfig, $frontmatter } = this
        return $frontmatter.author || $themeConfig.author
      },
      foo() {
        const { $themeConfig, $frontmatter } = this
        return $frontmatter.foo || $themeConfig.foo
      }
    }
  })
}

Run Code Online (Sandbox Code Playgroud)
  {{ author }}  //- 'Name'
  {{ foo }} //- 'bar
Run Code Online (Sandbox Code Playgroud)

Vuepress 配置文档 Vuepress 应用程序级别增强