用vue实现换服
使用 Vue 实现换肤功能
动态切换 CSS 变量
在 Vue 项目中可以通过动态修改 CSS 变量实现换肤。在根元素定义变量,通过 JavaScript 动态修改这些变量的值。
:root {
--primary-color: #409EFF;
--background-color: #f5f7fa;
}
在组件中使用这些变量:
.container {
background-color: var(--background-color);
color: var(--primary-color);
}
通过 Vue 动态修改变量:
methods: {
changeTheme(theme) {
document.documentElement.style.setProperty('--primary-color', theme.primaryColor)
document.documentElement.style.setProperty('--background-color', theme.backgroundColor)
}
}
使用 CSS 预处理器变量
如果项目使用 Sass 或 Less,可以创建多套主题文件,通过动态加载不同主题文件实现换肤。

创建主题文件 theme-light.scss:
$primary-color: #409EFF;
$background-color: #f5f7fa;
创建主题文件 theme-dark.scss:
$primary-color: #304156;
$background-color: #1f2d3d;
在 Vue 组件中动态加载主题:

methods: {
loadTheme(themeName) {
import(`@/styles/themes/theme-${themeName}.scss`)
}
}
使用 Vuex 管理主题状态
在 Vuex 中存储当前主题信息,便于全局管理:
const store = new Vuex.Store({
state: {
currentTheme: 'light'
},
mutations: {
setTheme(state, theme) {
state.currentTheme = theme
}
}
})
组件中通过计算属性获取当前主题:
computed: {
currentTheme() {
return this.$store.state.currentTheme
}
}
实现主题持久化
使用 localStorage 保存用户选择的主题,确保刷新后主题不变:
methods: {
changeTheme(theme) {
this.$store.commit('setTheme', theme)
localStorage.setItem('user-theme', theme)
this.applyTheme(theme)
},
applyTheme(theme) {
// 应用主题的具体逻辑
},
initTheme() {
const savedTheme = localStorage.getItem('user-theme') || 'light'
this.changeTheme(savedTheme)
}
},
created() {
this.initTheme()
}
完整组件示例
<template>
<div class="app" :class="`theme-${currentTheme}`">
<button @click="toggleTheme">切换主题</button>
<!-- 其他内容 -->
</div>
</template>
<script>
export default {
data() {
return {
themes: {
light: {
primaryColor: '#409EFF',
backgroundColor: '#f5f7fa'
},
dark: {
primaryColor: '#304156',
backgroundColor: '#1f2d3d'
}
}
}
},
computed: {
currentTheme() {
return this.$store.state.currentTheme
}
},
methods: {
toggleTheme() {
const newTheme = this.currentTheme === 'light' ? 'dark' : 'light'
this.$store.commit('setTheme', newTheme)
this.applyTheme(this.themes[newTheme])
localStorage.setItem('user-theme', newTheme)
},
applyTheme(theme) {
Object.keys(theme).forEach(key => {
document.documentElement.style.setProperty(
`--${key}`,
theme[key]
)
})
}
},
created() {
const savedTheme = localStorage.getItem('user-theme') || 'light'
this.$store.commit('setTheme', savedTheme)
this.applyTheme(this.themes[savedTheme])
}
}
</script>
<style>
.app {
background-color: var(--backgroundColor);
color: var(--primaryColor);
}
</style>






