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>
相关推荐
脑袋大大的18 分钟前
uni-app x开发避坑指南:拯救被卡顿的UI线程!
开发语言·前端·javascript·vue.js·ui·uni-app·uts
ayas1231931 分钟前
CSS学习
前端·css·学习
土族程序员35 分钟前
JavaFX CSS @font-face 错误全面分析 loadStylesheetUnPrivileged / reportException
java·css·javafx
人生在勤,不索何获-白大侠37 分钟前
day25——HTML & CSS 前端开发
前端·css·html
Running_C44 分钟前
Content-Type的几种类型
前端·面试
前端Hardy44 分钟前
10 分钟搞定婚礼小程序?我用 DeepSeek 把同学的作业卷成了范本!
前端·javascript·微信小程序
Tminihu1 小时前
前端大文件上传的时候,采用切片上传的方式,如果断网了,应该如何处理
前端·javascript
颜酱1 小时前
理解vue3中的compiler-core
前端·javascript·vue.js
果粒chenl1 小时前
06-原型和原型链
前端·javascript·原型模式
谢尔登1 小时前
【JavaScript】手写 Object.prototype.toString()
前端·javascript·原型模式