上一篇文章只配置了两个主题,现在我们来配置多主题。 前面步骤参:Vue3+TypeScript+Vuetify+Vite 实现动态主题切换 - TeHub
我们打开vuetify.ts文件,修改我们之前定义的主题
// Styles import '@mdi/font/css/materialdesignicons.css' import 'vuetify/styles' // Vuetify import { createVuetify } from 'vuetify' const customDarkTheme = { dark: true, colors: { background: "#15202b", surface: "#15202b", primary: "#3f51b5", secondary: "#03dac6", error: "#f44336", info: "#2196F3", success: "#4caf50", warning: "#fb8c00", }, }; const customLightTheme = { dark: false, colors: { background: '#808080', surface: '#6200EE', primary: '#6200EE', 'primary-darken-1': '#3700B3', secondary: '#03DAC6', 'secondary-darken-1': '#018786', error: '#B00020', info: '#2196F3', success: '#4CAF50', warning: '#FB8C00', }, }; const customTheme = { dark: false, colors: { background: '#34A853', surface: '#FF0101', primary: '#FF0101', 'primary-darken-1': '#FF0101', secondary: '#03DAC6', 'secondary-darken-1': '#018786', error: '#B00020', info: '#2196F3', success: '#4CAF50', warning: '#FF0101', }, }; export default createVuetify( // https://vuetifyjs.com/en/introduction/why-vuetify/#feature-guides { theme: { defaultTheme: 'light', themes: { customDarkTheme, customLightTheme, customTheme, } } } )
使用App.vue页面,引入useTheme() 全局改变主题色。
<template> <v-app > <v-main> <!-- <v-btn @click="toggleTheme">点击切换主题</v-btn>--> <v-btn @click="setTheme(0)">light</v-btn> <v-btn @click="setTheme(1)">dark</v-btn> <v-btn @click="setTheme(2)">customTheme</v-btn> <v-btn @click="setTheme(3)">customLightTheme</v-btn> <v-btn @click="setTheme(4)">customDarkTheme</v-btn> <v-card theme="light">测试测试...</v-card> <v-theme-provider theme="customLightTheme"> <v-card>测试测试...</v-card> </v-theme-provider> <HelloWorld/> </v-main> </v-app> </template> <script setup lang="ts"> import {ref} from 'vue' import HelloWorld from './components/HelloWorld.vue' import {useTheme} from "vuetify"; //使用useTheme() 获取主题,useTheme()是由Vuetify提供的 const theme = useTheme(); //包含Vuetify默认的浅色和深色主题以及我们自定义的主题 const myThemes = ["light","dark","customTheme","customLightTheme","customDarkTheme"] const setTheme = (index:number) => { //全局修改主题theme theme.global.name.value = myThemes[index] } // const toggleTheme = () => { // console.log('111111',theme.value) // theme.value = theme.value === 'light' ? 'dark' : 'light' // } </script>
可以通过设置theme属性来定义主题颜色,也可以用使用v-theme-provider来定义主题色