vue实现页面换肤
使用CSS变量实现换肤
在Vue项目中,可以通过CSS变量动态修改主题色。定义全局CSS变量,在组件中引用这些变量,通过JavaScript动态修改变量的值。
/* 全局样式文件 */
:root {
--primary-color: #409EFF;
--background-color: #f5f7fa;
}
.dark-theme {
--primary-color: #304156;
--background-color: #1f2d3d;
}
// Vue组件中切换主题
methods: {
toggleTheme() {
document.body.classList.toggle('dark-theme')
}
}
使用SCSS变量与webpack配合
通过webpack的sass-loader配置,在编译时动态注入SCSS变量,实现主题切换。
// theme.scss
$primary-color: var(--primary-color, #409EFF);
$background-color: var(--background-color, #f5f7fa);
// vue.config.js
module.exports = {
css: {
loaderOptions: {
sass: {
additionalData: `@import "@/styles/theme.scss";`
}
}
}
}
动态加载样式文件
准备多套主题CSS文件,通过动态加载不同CSS文件实现换肤功能。
// 主题切换方法
function loadTheme(themeName) {
const link = document.createElement('link')
link.rel = 'stylesheet'
link.href = `/themes/${themeName}.css`
document.head.appendChild(link)
}
使用Vuex管理主题状态
结合Vuex全局状态管理,统一管理当前应用主题。
// store/modules/theme.js
export default {
state: {
currentTheme: 'light'
},
mutations: {
setTheme(state, theme) {
state.currentTheme = theme
}
}
}
组件化主题切换控件
创建可复用的主题切换组件,方便在不同页面使用。
<template>
<div class="theme-switcher">
<button @click="setTheme('light')">Light</button>
<button @click="setTheme('dark')">Dark</button>
</div>
</template>
<script>
export default {
methods: {
setTheme(theme) {
this.$store.commit('theme/setTheme', theme)
document.body.className = theme + '-theme'
}
}
}
</script>
持久化主题选择
使用localStorage保存用户选择的主题,实现刷新后保持主题设置。
// 在Vuex中
actions: {
initTheme({ commit }) {
const savedTheme = localStorage.getItem('theme') || 'light'
commit('setTheme', savedTheme)
document.body.className = savedTheme + '-theme'
},
changeTheme({ commit }, theme) {
localStorage.setItem('theme', theme)
commit('setTheme', theme)
document.body.className = theme + '-theme'
}
}






