前端主题切换

144 阅读1分钟
theme: smartblue --- 一、项目背景 项目需要两套主题,深色模式跟浅色模式,文字图片也随模式的变化而变化,找了几种解决方法,选了其中一个。参考了vue官网

7932366654114e048419e3e679e7c6e7~tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.webp

二、具体代码实现 在app.vue里面写

onMounted(() => {
  getThemeColor('light');
});
// 深色模式和浅色模式区分
function getThemeColor(themeColor) {
  console.log(123, themeColor);
  if (themeColor === 'dark') {
    // document.body.className = themeColor;
    document.querySelector('html').className = themeColor;
    store.commit('user/setThemeColor', 'dark');
  } else {
    document.querySelector('html').className = themeColor;
    store.commit('user/setThemeColor', 'light');
  }
}
<style>
html.dark {
  color-scheme: dark;
}
/* 定义根作用域下的变量(浅色模式下) */
:root {
  --theme-color: #ffffffe6;
  --theme-title-active-color: #248cf8;
  --theme-title-normal-color: #4d597d;
  --theme-subtitle-active-color: #1f1f4e;
  --theme-bg-color: #ffffff;
  --theme-date-active-color: rgba(36, 140, 248, 0.08);
  --theme-text-bg-color: rgba(31, 31, 78, 0.8);
  --theme-title-color: #1f1f4e;
  --theme-text-color: #919dab;
  --theme-price-color: #f85f60;
  --theme-order-btn-color: linear-gradient(249deg, #2cabf0 0%, #2663ff 100%);
  --theme-disabled-btn-color: #919dab;
  --theme-settlement-btn-color: linear-gradient(250deg, #ff9c51 0%, #ec4881 100%);
  --theme-delete-color: #eff1f3;
  --theme-delete-text-color: #919dab;
  --theme-week-bg-color: rgba(239, 241, 243, 0.5);
  --theme-week-active-color: #248cf8;
  --theme-week-normal-text: #fff;
  --theme-cancel-bg: rgba(248, 95, 96, 0.1);
  --theme-cancel-text: #f85f60;
  --theme-line-color: #dadee3;
  --theme-close-bg-color: rgba(255, 255, 255, 0.1);
  --theme-close-border-color: rgba(255, 255, 255, 0.4);
  --theme-pay-bg-color: #f8f8ff;
  --theme-pay-text-color: #404040;
  --theme-name-bg-color: #ecf6ff;
}
/* 更改dark类名下变量的取值(深色模式下) */
.dark {
  --theme-color: red;
  --theme-background: #333;
}

具体代码里使用

background: var(--theme-color);

具体参考文章:juejin.cn/post/713459…