Vue主题色切换实现方案(CSS 变量 + 类名切换)

  1. 定义主题变量
javascript 复制代码
// styles/themes.scss
:root {
  --primary-color: #314099;
  --secondary-color: #1E3968;
  --text-color: #2c44ce;
}

[data-theme="红系主题"] {
  --primary-color: #d74146;
  --secondary-color: #c20707;
  --text-color: #db3b3b;
}
  1. 在组件中使用变量
javascript 复制代码
<template>
  <div class="app" :data-theme="currentTheme">
    <button @click="toggleTheme">切换主题</button>
    <div class="content">主题色内容</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentTheme: '蓝系主题'
    }
  },
  methods: {
    toggleTheme() {
      this.currentTheme = this.currentTheme === '蓝系主题' ? '红系主题' : '蓝系主题';
      localStorage.setItem('theme', this.currentTheme); // 保存到本地存储
    }
  },
  mounted() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) this.currentTheme = savedTheme;
  }
}
</script>

<style lang="scss">
@import '@/styles/themes.scss';

.content {
  color: var(--text-color);
  background-color: var(--primary-color);
  padding: 20px;
  transition: all 0.3s ease;
}
</style>
相关推荐
计算机魔术师6 分钟前
英伟达要投100亿美元入股Anthropic,史上最大IPO的底牌
前端
yume_sibai1 小时前
02-Flutter进阶开发
前端·flutter
a1117761 小时前
莱茵生命终端 网页 html
前端·开源
水月清辉2 小时前
CSS 常用语法详解
前端·css
梨涡泥窝2 小时前
JavaWeb——基于 Spring Boot + Vue 的图书管理系统的设计与实现
vue.js·spring boot·后端
Eric_见嘉2 小时前
打开这个 VSC 设置「组件引用位置」和数量就都清楚了
前端·typescript·visual studio code
李高钢2 小时前
Python Tornado 框架入门:从零搭建你的第一个异步 Web 应用
前端·python·tornado
宁风3 小时前
JavaScript:函数体系-1
前端·javascript
mmsx3 小时前
Android 手簿 ADB 无线调试全攻略:USB 转 WiFi 一键连接
android·前端
guwentian3 小时前
Rolldown vs esbuild vs Webpack:Rust 打包器大战我们该怎么选
前端·webpack·rust·esbuild