Vue + Scss项目中实现自定义颜色主题的动态切换

当时面试的时候遇到面试官问的一个问题如何实现自定义颜色主题切换,当时我做的只是elementUIPlus提供的暗黑和默认主题切换​​​​​​​


theme.scss

// 增加自定义主题类型
$themes: (
  light: (/* 原有配置保持不变 */),
  dark: (/* 原有配置保持不变 */),
  custom: () // 空映射用于自定义主题
);

// 新增CSS变量定义方式
:root {
  // 原有主题变量...
  
  // 自定义主题变量
  --custom-primary-color: #409eff;
  --custom-background-color: #ffffff;
  --custom-text-color: #303133;
}

main.ts

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import { initCustomTheme } from './utils/themeManager' // 新增导入

const app = createApp(App)

app.use(ElementPlus)

// 新增自定义主题初始化
initCustomTheme()
app.mount('#app')

 themeManager.ts

// 新增自定义主题设置方法
export const setCustomTheme = (colors: {
  primary: string
  background: string
  text: string
}) => {
  // 更新CSS变量
  document.documentElement.style.setProperty('--custom-primary-color', colors.primary)
  document.documentElement.style.setProperty('--custom-background-color', colors.background)
  document.documentElement.style.setProperty('--custom-text-color', colors.text)
  
  // 应用自定义主题
  document.documentElement.setAttribute('data-theme', 'custom')
  ElConfigProvider.setGlobalConfig({
    theme: {
      primary: colors.primary
    }
  })
  
  // 存储自定义配置
  localStorage.setItem('customTheme', JSON.stringify(colors))
}

// 初始化自定义主题
export const initCustomTheme = () => {
  const saved = localStorage.getItem('customTheme')
  if (saved) {
    const colors = JSON.parse(saved)
    setCustomTheme(colors)
  }
}

ThemeCustomizer.vue





你可能感兴趣的:(vue.js,scss,前端)