vue主题色实现
实现 Vue 主题色的方法
使用 CSS 变量动态切换主题色
在 src/assets/styles 目录下创建 theme.css 文件,定义主题色变量:
:root {
--primary-color: #409EFF;
--secondary-color: #67C23A;
}
.dark-theme {
--primary-color: #304156;
--secondary-color: #4F88C6;
}
在 main.js 中导入样式文件:
import '@/assets/styles/theme.css'
组件中使用 CSS 变量:
<template>
<button :style="{ backgroundColor: 'var(--primary-color)' }">按钮</button>
</template>
切换主题的 JavaScript 代码:
function toggleTheme() {
document.documentElement.classList.toggle('dark-theme')
}
使用 Vuex 管理主题状态
安装必要依赖:
npm install vuex
创建 store/modules/theme.js:
const state = {
currentTheme: 'light'
}
const mutations = {
SET_THEME(state, theme) {
state.currentTheme = theme
}
}
export default {
namespaced: true,
state,
mutations
}
在组件中切换主题:

methods: {
changeTheme() {
const newTheme = this.$store.state.theme.currentTheme === 'light' ? 'dark' : 'light'
this.$store.commit('theme/SET_THEME', newTheme)
document.documentElement.className = newTheme + '-theme'
}
}
使用 SCSS 变量和混合
创建 src/assets/styles/variables.scss:
$themes: (
light: (
primary-color: #409EFF,
secondary-color: #67C23A
),
dark: (
primary-color: #304156,
secondary-color: #4F88C6
)
);
创建 src/assets/styles/mixins.scss:
@mixin theme-aware($key, $color) {
@each $theme-name, $theme-color in $themes {
.#{$theme-name}-theme & {
#{$key}: map-get($theme-color, $color)
}
}
}
组件中使用:
.button {
@include theme-aware('background-color', 'primary-color');
}
使用第三方库
安装 vue-theme-switcher:

npm install vue-theme-switcher
基本使用:
import Vue from 'vue'
import ThemeSwitcher from 'vue-theme-switcher'
Vue.use(ThemeSwitcher, {
themes: {
light: {
primary: '#409EFF'
},
dark: {
primary: '#304156'
}
}
})
在组件中切换:
this.$theme.set('dark')
响应式主题切换实现
创建主题监听器:
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)')
prefersDark.addListener(e => {
const theme = e.matches ? 'dark' : 'light'
this.$store.commit('theme/SET_THEME', theme)
})
持久化主题选择:
// 保存到localStorage
localStorage.setItem('user-theme', theme)
// 初始化时读取
const savedTheme = localStorage.getItem('user-theme') || 'light'
this.$store.commit('theme/SET_THEME', savedTheme)






