// 在 App.vue文件下定义即可
// useDark() 和 useToggle() 均需要安装 @vueuse/core 包 即可使用
npm install element-plus --save 安装 Element-Plus
npm install @vueuse/core --save 安装 @vueuse/core
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
console.log('dark');
useCommonStore.theme = 'dark'
const isDark = useDark()
const toggleDark = useToggle(isDark)
} else {
console.log('light');
useCommonStore.theme = 'light'
}
1、首先,我使用的是Element-Plus,如果你没有使用Element-plus也是可以做的。
2、不论是否使用了Element-plus,若是在系统切换暗黑模式后想自定义颜色应用的字体颜色或者其他样式,可以新建个公共css类,如下
:root {
--btnBlackColor: #1D1D1F;
--btnRedColor: #DB1528;
--btnWhiteColor: #ffffff;
--textBlackColor: #1D1D1F;
--textRedColor: #DB1528;
--bgRedColor: #DB1528;
--bgBlackColor: #1D1D1F;
--bgWhiteColor: #fff;
}
// 暗黑模式
html.dark {
--btnBlackColor: #1D1D1F;
--btnRedColor: #DB1528;
--btnWhiteColor: #ffffff;
--textBlackColor: #1D1D1F;
--textRedColor: #DB1528;
--bgRedColor: #DB1528;
--bgBlackColor: #1D1D1F;
--bgWhiteColor: #fff;
}
// 可对Element组件样式自定义样式
.el-icon {
color: var(--textBlackColor) !important;
}
.el-input__inner {
color: var(--textBlackColor) !important;
}
只需要在main.js或者main.ts中引入这个css文件即可生效
// main.ts
import './public/theme.css'
页面中使用暗黑模式下的样式,如:
color:var(
--bgRedColor);
亦或者你可以在此修改element-plus的样式
--el-bg-color-page: #0a0a0a;
--el-bg-color: #141414;
现在你可以体验切换暗黑模式了