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>
相关推荐
coder_pig22 分钟前
跟🤡杰哥一起学Flutter (三十四、玩转Flutter手势✋)
前端·flutter·harmonyos
万少28 分钟前
01-自然壁纸实战教程-免费开放啦
前端
独立开阀者_FwtCoder30 分钟前
【Augment】 Augment技巧之 Rewrite Prompt(重写提示) 有神奇的魔法
前端·javascript·github
yuki_uix41 分钟前
AI辅助网页设计:从图片到代码的实践探索
前端
我想说一句41 分钟前
事件机制与委托:从冒泡捕获到高效编程的奇妙之旅
前端·javascript
陈随易42 分钟前
MoonBit助力前端开发,加密&性能两不误,斐波那契测试提高3-4倍
前端·后端·程序员
小飞悟1 小时前
你以为 React 的事件很简单?错了,它暗藏玄机!
前端·javascript·面试
中微子1 小时前
JavaScript 事件机制:捕获、冒泡与事件委托详解
前端·javascript
Whoisshutiao1 小时前
网安-XSS-pikachu
前端·安全·网络安全
惊鸿2871 小时前
Taro3+小程序Canvas动态生成海报和二维码分享到朋友圈
前端