Introduction
Managing multiple themes in Vue.js applications can be complex, especially with more than two themes. The traditional method of toggling a .dark class leads to cumbersome CSS overrides and lacks scalability. Enter vue-multiple-themes, a dedicated library for dynamic theme management in Vue 2 & 3.
Core Features
- CSS Custom Properties: Themes are managed through
--vmt-*variables, injected at the target element. This allows for seamless theme switching without re-rendering components. - Reactive Theme Handling: Utilize the
useTheme()composable throughout your component tree for stateful theme management. - Preset Themes: Start with seven built-in themes like
light,dark,sepia,ocean,forest,sunset, andwinter. - WCAG Compliance: Built-in utilities for contrast checking and palette generation ensure accessibility.
Installation and Setup
To get started, run:
pnpm add vue-multiple-themes
Supports Vue 2.7+ and Vue 3 with no additional runtime dependencies beyond Vue itself.
Quick Start for Vue 3
Register the plugin in main.ts:
const app = createApp(App);
app.use(VueMultipleThemesPlugin, {
defaultTheme: 'dark',
strategy: 'attribute',
persist: true,
});
app.mount('#app');
Use useTheme() in your components:
<script setup lang="ts">
const { currentTheme, setTheme, themes } = useTheme({ themes: PRESET_THEMES });
</script>
<template>
<button v-for="t in themes" :key="t.name" @click="setTheme(t.name)">
{{ t.label }}
</button>
</template>
TailwindCSS Integration
Integrate with TailwindCSS by adding the plugin:
const { createVmtPlugin } = require('vue-multiple-themes/tailwind');
module.exports = { plugins: [createVmtPlugin()] };
This allows for dynamic styling based on the active theme.
Dynamic Theme Generation
Create custom themes on-the-fly:
const { light, dark } = generateThemePair('#6366f1');
const scale = generateColorScale('#6366f1', 9);
Perfect for applications needing brand-specific themes.
WCAG Utilities
Ensure your themes meet accessibility standards with pure, SSR-safe functions:
contrastRatio('#6366f1', '#ffffff'); // Returns 4.54
autoContrast('#6366f1'); // Returns '#ffffff'
API Overview
The useTheme() API offers flexibility:
- themes: List of available themes.
- defaultTheme: Set the initial theme.
- strategy: Choose between
attribute,class, orbothfor DOM application. - persist: Save theme settings in
localStorage.
Vue 2 Compatibility
For Vue 2, simply use:
Vue.use(VueMultipleThemesPlugin, { defaultTheme: 'light' });
Explore more on GitHub and npm for documentation and examples.