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>
相关推荐
用户2181697049301 小时前
Flutter(四)Dart语法 空安全 运算符 流程控制
前端
许彰午1 小时前
政务督办的分合模式:主办协办的并发审批
前端·javascript·政务
用户69371750013841 小时前
AI时代,程序员该往哪走?
前端·后端
陳陈陳1 小时前
🚀 前端流式输出革命:SSE + BFF 架构从零到一实战指南
vue.js·架构·node.js
ttwuai1 小时前
GoFrame 后台日志清空失败:无 WHERE 删除为什么被拦住
前端·golang
易筋紫容1 小时前
创建型模式:对象的诞生艺术
开发语言·前端·javascript
半句唐诗1 小时前
我是如何通过 Access Token 成功发布第一个 npm 包的
前端·npm·node.js
程序员黑豆1 小时前
鸿蒙应用开发:@Provider 与 @Consumer 跨组件双向同步详解
前端·harmonyos
paopaokaka_luck2 小时前
基于springboot3+vue3的智能文库平台(AI智能搜索、AI智能汇总、实时在线状态展示、多格式文档预览与富文本编辑、Echarts图形化分析)
前端·网络·spring boot·网络协议·echarts
牧艺2 小时前
cos-design PhotoAlbum:用 CSS 3D 做一个「能翻页」的实体相册
前端·css·交互设计