vue实现主题
Vue 实现主题的方法
使用 CSS 变量动态切换主题
定义全局 CSS 变量,通过修改这些变量实现主题切换。在 Vue 的根组件或全局样式中定义变量:
:root {
--primary-color: #42b983;
--background-color: #ffffff;
--text-color: #2c3e50;
}
.dark-theme {
--primary-color: #1e88e5;
--background-color: #121212;
--text-color: #ffffff;
}
在 Vue 组件中通过类名切换主题:
<template>
<div :class="{'dark-theme': isDark}">
<!-- 组件内容 -->
</div>
</template>
<script>
export default {
data() {
return {
isDark: false
}
},
methods: {
toggleTheme() {
this.isDark = !this.isDark
}
}
}
</script>
使用 Vuex 管理主题状态
对于大型应用,可以使用 Vuex 集中管理主题状态:
// store.js
export default new Vuex.Store({
state: {
darkMode: false
},
mutations: {
toggleTheme(state) {
state.darkMode = !state.darkMode
}
}
})
在组件中使用:
<template>
<button @click="toggleTheme">切换主题</button>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
computed: {
...mapState(['darkMode'])
},
methods: {
...mapMutations(['toggleTheme'])
}
}
</script>
使用第三方库实现主题
Vue 生态中有专门的主题管理库,如 vue-theme-switcher:
安装:
npm install vue-theme-switcher
使用:
import Vue from 'vue'
import ThemeSwitcher from 'vue-theme-switcher'
Vue.use(ThemeSwitcher, {
themes: {
light: {
primary: '#42b983'
},
dark: {
primary: '#1e88e5'
}
}
})
在组件中切换:
this.$theme.set('dark')
持久化主题选择
将用户选择的主题保存在 localStorage 中:
// 保存主题
localStorage.setItem('theme', 'dark')
// 读取主题
const savedTheme = localStorage.getItem('theme') || 'light'
this.$theme.set(savedTheme)
响应系统主题变化
检测用户系统主题偏好:
const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
darkModeMediaQuery.addListener((e) => {
const darkModeOn = e.matches
this.$theme.set(darkModeOn ? 'dark' : 'light')
})






