vue一键换肤

1.CSS变量方案

优点:

  • 性能好,切换即时生效
  • 实现简单,维护方便
  • 支持动态计算(如色阶)
  • 浏览器原生支持

2. 动态切换 style 标

(1)首先进行变量配置,比如我现在有两个主题:

// 主题配置
export const themeConfig = {
  default: {
    '--primary-color': '#409eff',
    '--primary-bg': '#ffffff',
    '--text-color': '#303133',
    // ... 其他变量
  },
  dark: {
    '--primary-color': '#67c23a',
    '--primary-bg': '#1f1f1f',
    '--text-color': '#ffffff',
    // ... 其他变量
  },
  // ... 其他主题
}

// 切换主题方法
export const changeTheme = (themeName: string) => {
  const theme = themeConfig[themeName]
  if (!theme) return
  
  const root = document.documentElement
  Object.keys(theme).forEach(key => {
    root.style.setProperty(key, theme[key])
  })
  
  // 保存主题设置
  localStorage.setItem('theme', themeName)
}

(2)设置全局scss变量 

:root {
  --primary-color: #409eff;
  --primary-bg: #ffffff;
  --text-color: #303133;
  // ... 其他变量
}

2.动态切换style样式方案

export const changeTheme = async (themeName: string) => {
  // 移除已存在的主题样式
  const existingStyle = document.getElementById('theme-style')
  if (existingStyle) {
    existingStyle.remove()
  }

  // 动态加载新主题样式
  try {
    const style = document.createElement('style')
    style.id = 'theme-style'
    
    // 动态导入主题文件
    const themeModule = await import(`@/assets/themes/${themeName}.scss`)
    style.textContent = themeModule.default
    
    document.head.appendChild(style)
    localStorage.setItem('theme', themeName)
  } catch (error) {
    console.error('主题加载失败:', error)
  }
}

3.cssModule方案

跟2类似

<template>
  <div :class="[themeClass.theme]">
    <!-- 应用内容 -->
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const currentTheme = ref('blue')
const themeClass = computed(() => {
  return require(`@/themes/${currentTheme.value}.module.scss`)
})
</script>

4.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值