vue实现项目主题切换

 项目主题切换小案例:


<template>
  <button @click="toggleTheme">切换主题</button>
  <div class="theme-box">这事一个切换验证</div>
</template>
  
<script setup>
import { ref, onMounted } from 'vue'


// 写法一
// const toggleTheme = () => {
  // const htmlEl = document.documentElement;
  // const currentTheme = htmlEl.getAttribute("data-theme");
  // const newTheme = currentTheme === "dark" ? "light" : "dark";
  // htmlEl.setAttribute("data-theme", newTheme);
// };

// onMounted(() => { toggleTheme() });


// 写法二
// 响应式主题状态
const theme = ref('light')

// 切换主题函数
function toggleTheme() {
  theme.value = theme.value === 'light' ? 'dark' : 'light'
}

// 在组件挂载时设置 data-theme 属性到 html 标签
onMounted(() => {
  document.documentElement.setAttribute('data-theme', theme.value)
})

// 监听 theme 变化,同步更新 html 的 data-theme 属性
watch(theme, (newVal) => {
  document.documentElement.setAttribute('data-theme', newVal)
})
</script>
  
<style>
/* 定义全局变量 */
:root[data-theme="light"] {
  --bg-color: rgb(206, 219, 156);
  --text-color: black;
}

:root[data-theme="dark"] {
  --bg-color: rgb(169, 123, 221);
  --text-color: white;
}
</style>
  
<style scoped>
.theme-box {
  width: 300px;
  height: 120px;
  background-color: var(--bg-color);
  color: var(--text-color); /* 使用定义的文本颜色变量 */
}
</style>

### 在 Vue3 中通过 CSS Variables 实现主题切换Vue3 应用中,可以通过动态修改根节点 (`:root`) 上的 CSS 变量来实现主题切换功能。以下是具体的实现方法及其细节。 --- #### 1. 定义全局 CSS 变量 首先,在项目的全局样式文件(如 `index.css` 或 `global.css`)中定义一组默认的 CSS 变量,用于表示不同主题的颜色和其他样式属性。 ```css /* src/styles/global.css */ :root { /* 默认浅色主题 */ --primary-color: #42b983; --background-color: #ffffff; --text-color: #000000; } .dark-theme { /* 深色主题 */ --primary-color: #ff5722; --background-color: #333333; --text-color: #ffffff; } ``` 在这里,`:root` 表示全局默认主题,而 `.dark-theme` 则代表深色模式下的覆盖样式[^1]。 --- #### 2. 创建主题切换逻辑 为了方便管理主题状态,可以使用 Vuex 存储当前选中的主题名称,并提供更改主题的方法。 ##### (1)Vuex Store 配置 创建一个简单的 Vuex store 来保存和更新主题设置。 ```javascript // src/store/index.js import { createStore } from 'vuex'; export default createStore({ state: { theme: 'light', // 初始化为浅色主题 }, mutations: { SET_THEME(state, themeName) { state.theme = themeName; document.documentElement.className = themeName === 'dark' ? 'dark-theme' : ''; // 修改文档根节点类名 }, }, actions: { changeTheme({ commit }, themeName) { commit('SET_THEME', themeName); }, }, }); ``` 这段代码实现了两个核心功能:一是存储当前主题的状态;二是通过修改 `documentElement` 的类名触发对应的主题样式生效[^2]。 --- #### 3. 构建主题选择器组件 接下来开发一个可复用的主题切换组件,允许用户手动选择不同的主题。 ```vue <!-- src/components/ThemeSwitcher.vue --> <template> <button @click="toggleTheme">{{ currentThemeText }}</button> </template> <script> export default { computed: { currentThemeText() { return this.$store.state.theme === 'light' ? '切换至暗黑模式' : '切换至明亮模式'; }, }, methods: { toggleTheme() { const newTheme = this.$store.state.theme === 'light' ? 'dark' : 'light'; this.$store.dispatch('changeTheme', newTheme); // 调用 Vuex action 更新主题 }, }, }; </script> ``` 此组件监听用户的点击行为,并调用 Vuex 的 `changeTheme` 方法完成实际的主题切换操作。 --- #### 4. 使用 unplugin-vue-cssvars 插件优化体验 对于更加复杂的场景,比如需要将 Vue 数据绑定到 CSS 变量中,可以引入第三方工具 **unplugin-vue-cssvars** 提供的支持。它使得我们能够在普通的 CSS 文件里直接访问 Vue 组件实例上的响应式数据作为变量值[^3]。 安装依赖: ```bash npm install unplugin-vue-cssvars -D ``` 配置 Vite 或 Webpack 工具链加载该插件: ```javascript // vite.config.js import vueCssVars from 'unplugin-vue-cssvars/vite'; export default { plugins: [ vueCssVars(), ], }; ``` 之后即可像下面这样编写更具互动性的样式规则: ```css .button { background-color: v-bind(primaryColor); color: white; } ``` 其中 `v-bind()` 函数会自动解析成对应的 Vue 属性或计算字段。 --- #### 总结 综上所述,Vue3 下基于 CSS Variables 的多主题解决方案主要分为三个部分:定义基础变量集合、构建集中化的状态管理系统以及设计直观易用的选择界面。同时配合现代化构建工具扩展其潜力,最终达成高效且优雅的结果。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温柔于心动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值