跳到主要内容

How to Use Vuetify’s Components in a VitePress Website

Step 1: Add Vuetify to your VitePress project

Installation

npm i vuetify

Configuration

Use vite-plugin-vuetify to import used components and directives automatically.

注意

The vite-plugin-vuetify plugin only works for Vue Single-File Components, when you use Vue in Markdown, you still need to manually import components and directives.

.vitepress/config.mts
import vuetify from 'vite-plugin-vuetify';

export default defineConfig({
// ...
vite: {
plugins: [vuetify()],
ssr: {
noExternal: ['vuetify'], // https://github.com/vuejs/vitepress/discussions/3578#discussioncomment-8495321
},
},
});

Initialization

.vitepress/theme/index.ts
import DefaultTheme from 'vitepress/theme';
import 'vuetify/styles';
import { createVuetify } from 'vuetify';

const vuetify = createVuetify({
ssr: true, // https://vuetifyjs.com/en/getting-started/installation/#ssr-caveats
});

export default {
...DefaultTheme,
enhanceApp({ app }) {
app.use(vuetify);
},
};

Step 2: Use vp-raw class to remove VitePress’s default styles from Vuetify’s components

Install postcss

npm i -D postcss

Transform CSS selectors

Use postcssIsolateStyles to transform all the CSS selector from related CSS files (typically base.css, vp-doc.css).

.(/docs)/postcss.config.mjs
import { postcssIsolateStyles } from 'vitepress';

export default {
plugins: [
postcssIsolateStyles({
includeFiles: [/base\.css/, /vp-doc\.css/],
}),
],
};

For example, CSS selector .xxx became .xxx:not(:where(.vp-raw, .vp-raw *)) so that it no longer takes effect on the element when the vp-raw class is present.

Apply vp-raw class to Vuetify’s components

Wrap Vuetify’s component with raw container

::: raw
<MyComponent />
:::

or directly add vp-raw class to it (or any of its parents)

<MyComponent class="vp-raw"/>

Vue supports resolving kebab-case tags to components registered using PascalCase. This means a component registered as MyComponent can be referenced inside a Vue template (or inside an HTML element rendered by Vue) via both <MyComponent> and <my-component>.

Step 3: Synchronize dark mode status from VitePress to Vuetify’s components

VitePress has a hook useData which returns page-specific data, which contains a field isDark. Watch this field to change the theme of the Vuetify components accordingly.

import { useData } from 'vitepress';
import { useTheme } from 'vuetify';
import { watchEffect } from 'vue';

const { isDark } = useData();
const theme = useTheme();
watchEffect(
() => {
theme.change(isDark.value ? 'dark' : 'light');
},
{
flush: 'post', // Post Watchers: https://vuejs.org/guide/essentials/watchers.html#post-watchers
},
);