How to Use Vuetify’s Components in a VitePress Website
Step 1: Add Vuetify to your VitePress project
Installation
- npm
- Yarn
- pnpm
- Bun
npm i vuetify
yarn add vuetify
pnpm add vuetify
bun add 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.
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
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
- Yarn
- pnpm
- Bun
npm i -D postcss
yarn add --dev postcss
pnpm add -D postcss
bun add --dev postcss
Transform CSS selectors
Use postcssIsolateStyles to transform all the CSS selector from related CSS files (typically base.css, vp-doc.css).
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
},
);