之前在项目中用了Sass的多主题切换,感觉太麻烦,后面发现直接用CSS的很方便,所以整理一下,希望可以帮到大家,也是对自己的积累。
第一步: 需要创建一个colorConfig.ts文件,用于配置主题信息 (我创建的目录是src/config/colorConfig.ts)
colorConfig.ts文件的主要定义的内容
const COLOR_MAP = {
theme1: {
color1: '#FFCDD2',
color2: '#E1BEE7',
color3: '#70767f',
color4: '#EF9A9A',
color5: '#F06292',
color6: '#7986CB',
color7: '#64B5F6',
},
theme2: {
color1: '#FF7043',
color2: '#4E342E',
color3: '#263238',
color4: '#FF6E40',
color5: '#DD2C00',
color6: '#616161',
color7: '#212121',
},
theme3: {
color1: '#E65100',
color2: '#FF6D00',
color3: '#1B5E20',
color4: '#827717',
color5: '#00C853',
color6: '#0091EA',
color7: '#00BFA5',
}
}
export type THEME_TYPE = keyof (typeof COLOR_MAP)
type THEME_ITEM = keyof (typeof COLOR_MAP['theme1'])
export function changeTheme (theme: THEME_TYPE = 'theme1'): void {
const themeList = Object.keys(COLOR_MAP[theme]) as THEME_ITEM[]
themeList.forEach((v: THEME_ITEM) => {
document.body.style.setProperty(`--${v}`, COLOR_MAP[theme][v])
})
}
第二步,根据接口获取当前主题信息,并进行切换设置
import { changeTheme } from '@/config/colorConfig'
created () {
const theme = localStorage.getItem('theme') || 'theme1'
store.commit('common/setTheme', theme)
changeTheme(theme)
getThemeInfo()
}
async getThemeInfo() {
const requestData = {
method: 'xxxx',
params: { method: 'xxx' }
}
const response = await this.$axios({
method: 'POST',
url: `${this.$baseUrl}/xxxx/xxxx/`,
data: requestData
}).catch(() => {
store.commit('common/setTheme', 'theme1')
changeTheme('theme1')
})
let { code, data } = response?.data || {}
if (code === '0000') {
const theme = data?.theme
store.commit('common/setTheme', theme ? theme : 'theme1')
changeTheme(theme ? theme : 'theme1')
} else {
store.commit('common/setTheme', 'theme1')
changeTheme('theme1')
}
}
第三步,切换主题时,更新缓存
import { changeTheme, THEME_TYPE } from '@/config/colorConfig'
themeChange(themeVal): void {
changeTheme(themeVal as THEME_TYPE)
store.commit('common/setTheme', themeVal)
localStorage.setItem('theme', themeVal)
}
第四步, 页面上使用css变量来动态展示颜色值
#app {
width: 100%;
height: 100%;
background-color: var(--color1);
box-sizing: border-box;
color: var(--color2);
font-size: 1rem;
}
效果图如下图所示


