Vue3 + Vuetifyで開発していると、デフォルトのテーマではなく
自分のプロダクト用のカラーテーマを作りたくなることがよくあります。
この記事では以下の事柄を解説します
- Vuetifyで独自テーマを作る方法
- themesディレクトリでの管理方法
- CSSからテーマカラーを使う方法
なぜカスタムテーマを作るのか
デフォルトの light / dark をそのまま使うと
- ブランドカラーが反映しづらい
- UIの統一が難しい
- CSSとテーマが分離して管理が破綻する
ディレクトリ構成
src/
plugins/
vuetify.ts
themes/
myLight.ts
types.ts
型定義(types.ts)
カスタムテーマで指定したcolor名の一覧を型として定義
export type AppThemeColors = {
primary: string
background: string
surface: string
text: string
brand: string
header: string
border?: string
success?: string
error?: string
}
カスタムテーマ(myLight.ts)
使用したい色を各プロパティに設定
import type { ThemeDefinition } from 'vuetify'
import type { AppThemeColors } from './types'
const colors: AppThemeColors = {
primary: '#AA3BFF',
background: '#FFFFFF',
surface: '#F9FAFB',
text: '#111827',
brand: '#AA3BFF',
header: '#111827',
border: '#E5E7EB',
success: '#22C55E',
error: '#EF4444',
}
export const myLight: ThemeDefinition = {
dark: false,
colors,
}
Vuetifyに適用
myLight.tsで定義したテーマをデフォルトで適用
// vuetifyのデフォルトCSSを読み込む
import 'vuetify/styles'
// vuetifyを使用する
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
import { myLight } from '@/design-system/themes/myLight'
export const vuetify = createVuetify({
components,
directives,
theme: {
defaultTheme: 'myLight',
themes: {
myLight: myLight,
},
},
})
CSSからテーマカラーを使う
VuetifyのテーマはCSS変数としても使えます。--v-theme-...で指定できます。
.header {
background: rgb(var(--v-theme-header));
color: rgb(var(--v-theme-text));
}
これで
Vuetifyコンポーネント以外でも色を統一できる
まとめ
- Vuetifyではテーマカラーを自作できる
- tsファイルで楽に管理できる
- cssからもテーマカラーを使用できる
今後の発展
- テーマ切り替えUI
- ダークモード対応