vue 实现换肤
实现全局主题切换
在Vue项目中实现换肤功能,可以通过CSS变量结合状态管理来实现全局主题切换。定义不同主题的CSS变量,通过动态修改这些变量来改变整体样式。
/* 定义默认主题变量 */
:root {
--primary-color: #409EFF;
--background-color: #f5f7fa;
--text-color: #303133;
}
/* 定义暗色主题变量 */
.dark-theme {
--primary-color: #3375b9;
--background-color: #22272e;
--text-color: #adbac7;
}
使用Vuex管理主题状态
通过Vuex存储当前主题状态,便于全局访问和修改。创建theme模块来管理主题相关状态和操作。
// store/modules/theme.js
export default {
state: {
currentTheme: 'light'
},
mutations: {
setTheme(state, theme) {
state.currentTheme = theme
}
},
actions: {
changeTheme({ commit }, theme) {
commit('setTheme', theme)
document.documentElement.className = theme + '-theme'
}
}
}
动态切换主题样式
在组件中通过计算属性获取当前主题,使用watch监听主题变化并动态修改HTML的class。这种方法可以实现无刷新切换主题。
export default {
computed: {
currentTheme() {
return this.$store.state.theme.currentTheme
}
},
watch: {
currentTheme(newVal) {
document.documentElement.className = newVal + '-theme'
}
}
}
组件内使用主题变量
在组件样式中使用CSS变量确保样式随主题变化。这种方式使组件样式与主题系统解耦,提高可维护性。
.component {
background-color: var(--background-color);
color: var(--text-color);
border-color: var(--primary-color);
}
持久化主题选择
使用localStorage保存用户选择的主题,确保刷新后保持主题一致。在Vuex的action中添加持久化逻辑。
actions: {
changeTheme({ commit }, theme) {
commit('setTheme', theme)
document.documentElement.className = theme + '-theme'
localStorage.setItem('user-theme', theme)
},
initTheme({ commit }) {
const savedTheme = localStorage.getItem('user-theme') || 'light'
commit('setTheme', savedTheme)
document.documentElement.className = savedTheme + '-theme'
}
}






