vue3 - Element Plus暗黑模式适配、切换及自定义颜色

GitHub Demo 地址

在线预览

Element Plus 2.2.0 版本开始支持暗黑模式,启用方式参考 Element Plus 官方文档 - 暗黑模式

demo通过Element PlusVueUse 的 useDark 方法实现具有自动数据持久性的响应式暗黑模式。

安装

npm install element-plus --save
npm install @vueuse/core --save

配置

main.ts导入下面一行代码就会支持暗黑模式

// main.ts
import 'element-plus/theme-chalk/dark/css-vars.css'

然后通过VueUse 的 useDark 方法切换暗黑模式

<template>
 <el-switch v-model="isDark" inline-prompt 
 :active-icon="IconEpMoon" 
 :inactive-icon="IconEpSunny" 
 active-color="var(--el-fill-color-dark)" 
 inactive-color="var(--el-color-primary)" 
 @change="toggleDark" />
 
</template>

<script setup lang="ts">

import IconEpSunny from '~icons/ep/sunny';
import IconEpMoon from '~icons/ep/moon';

const isDark = useDark()
const toggleDark = () => useToggle(isDark)

</script>

自定义全局使用的暗黑模式颜色

有时需要自定义一些可全局使用的颜色,并且支持暗黑模式
可在 import 'element-plus/theme-chalk/dark/css-vars.css'之后导入一个自定义的style文件,如base.scss,
然后在内部实现自定义的颜色

:root {
  --bPageBgColor: #f5f5f5;
  --bTextColor: #000;
  --bBgColor: var(--el-bg-color);
  --bBorderColor: var(--el-input-border-color);
  --bDialogBgColor: var(--el-dialog-bg-color);

  // single page use
  --roleHeaderBgColor: #f1f1f1;
  --selectRowBgColor: #e8f4ff;
}

html.dark {
  --bPageBgColor: #0a0a0a;
  --bTextColor: #fff;
  // --el-bg-color-page: #0a0a0a;
  // --el-bg-color: #141414;

  // single page use
  --roleHeaderBgColor: #0e0e0e;
  --selectRowBgColor: #414243;
}

然后在页面的css中使用设置的自定义颜色

 	color: var(--bTextColor);

效果如下

vue3 - Element Plus暗黑模式适配、切换及自定义颜色_第1张图片

vue3 - Element Plus暗黑模式适配、切换及自定义颜色_第2张图片

vue3 - Element Plus暗黑模式适配、切换及自定义颜色_第3张图片vue3 - Element Plus暗黑模式适配、切换及自定义颜色_第4张图片

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