vue项目实现换肤功能
实现动态主题切换
Vue项目可以通过CSS变量结合状态管理实现动态换肤功能。定义主题色变量在根元素,通过修改这些变量实现皮肤切换。
:root {
--primary-color: #409EFF;
--secondary-color: #67C23A;
--text-color: #303133;
}
使用Vuex管理主题状态
在Vuex中存储当前主题信息,提供切换主题的mutation方法。
// store/modules/theme.js
export default {
state: {
currentTheme: 'light',
themes: {
light: {
'--primary-color': '#409EFF',
'--secondary-color': '#67C23A'
},
dark: {
'--primary-color': '#324157',
'--secondary-color': '#3A8EE6'
}
}
},
mutations: {
setTheme(state, themeName) {
state.currentTheme = themeName
}
}
}
动态应用主题样式
创建主题切换方法,遍历主题变量并应用到文档根元素。
methods: {
changeTheme(themeName) {
this.$store.commit('setTheme', themeName)
const theme = this.$store.state.theme.themes[themeName]
Object.keys(theme).forEach(key => {
document.documentElement.style.setProperty(key, theme[key])
})
}
}
组件中使用主题变量
在组件样式中使用CSS变量确保颜色一致性。
.button {
background-color: var(--primary-color);
color: white;
}
持久化主题选择
使用localStorage保存用户选择的主题,在应用初始化时加载。
created() {
const savedTheme = localStorage.getItem('theme') || 'light'
this.changeTheme(savedTheme)
},
watch: {
'$store.state.theme.currentTheme'(newVal) {
localStorage.setItem('theme', newVal)
}
}
实现主题切换组件
创建主题选择器组件供用户交互。
<template>
<div class="theme-switcher">
<button
v-for="(theme, name) in themes"
:key="name"
@click="changeTheme(name)"
>
{{ name }}
</button>
</div>
</template>
处理系统主题偏好
检测用户系统主题偏好并自动匹配。
mounted() {
const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
darkModeMediaQuery.addListener(e => {
this.changeTheme(e.matches ? 'dark' : 'light')
})
if(darkModeMediaQuery.matches) {
this.changeTheme('dark')
}
}
扩展多主题支持
通过增加theme对象中的配置项,可以轻松扩展更多主题方案。
themes: {
light: { /*...*/ },
dark: { /*...*/ },
ocean: {
'--primary-color': '#1E88E5',
'--secondary-color': '#00ACC1'
}
}






