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>
相关推荐
一嘴一个橘子21 小时前
vue.js 视频截取为 gif - 2(将截取到的gif 转换为base64 、file)
vue.js
Mintopia21 小时前
🤖 算法偏见修正:WebAI模型的公平性优化技术
前端·javascript·aigc
Mintopia21 小时前
🧩 TypeScript防御性编程:让Bug无处遁形的艺术
前端·typescript·函数式编程
JarvanMo21 小时前
🔔 Flutter 本地通知: 吸引用户的完整指南—即使在他们离线时也能实现
前端
你想考研啊21 小时前
一、redis安装(单机)和使用
前端·数据库·redis
江城开朗的豌豆21 小时前
小程序与H5的“握手言和”:无缝嵌入与双向通信实战
前端·javascript·微信小程序
天蓝色的鱼鱼21 小时前
React 19 发布一年后:对比 React 18,带来了哪些惊喜与变革
前端·react.js
你的电影很有趣21 小时前
lesson73:Vue渐进式框架的进化之路——组合式API、选项式对比与响应式新范式
javascript·vue.js
江城开朗的豌豆21 小时前
小程序静默更新?用户却无感?一招教你“强提醒”
前端·javascript·微信小程序
小张成长计划..21 小时前
VUE工程化开发模式
前端·javascript·vue.js