Skip to content

如何在 Vitepress 中添加自定义组件?

在使用 Vitepress 构建文档网站时,有时候我们会希望添加一些自定义组件来增强页面的功能和展示效果。

那么,到底该如何在 Vitepress 中添加自定义组件呢?

一、准备工作

我们得有一个 Vitepress 项目。如果您还没有创建,赶紧搭建起来。创建好项目后,确保您对项目的结构和配置有一定的了解。

二、创建自定义组件

接下来就是创建自定义组件啦。假设我们要创建一个简单的自定义组件,叫做 MyCustomComponent.vue

html
<template>
  <div>
    <h2>这是我的自定义组件!</h2>
    <p>这里可以添加更多自定义内容</p>
  </div>
</template>

<script>
export default {
  name: "MyCustomComponent",
};
</script>

<style scoped>
/* 可以添加自定义样式 */
h2 {
  color: red;
}
</style>

有了这个组件,还得知道怎么把它“用起来”。

三、在 Vitepress 中注册和使用自定义组件

在 Vitepress 中,我们需要在 .vitepress/config.js 文件中进行注册。

javascript
import { defineConfig } from "vitepress";

export default defineConfig({
  themeConfig: {
    // 注册自定义组件
    vitepressPlugin: {
      components: ["MyCustomComponent"],
    },
  },
});

注册完成后,就可以在 Markdown 文件中像使用内置组件一样使用我们的自定义组件。

markdown
<MyCustomComponent />

是不是很简单?成功地在 Vitepress 中添加了自定义组件。

通过以上步骤,您就可以在 Vitepress 中尽情发挥,添加各种满足您需求的自定义组件。