Skip to content
当前页

夜间模式

介绍

项目已经内置了夜间模式切换,只需配置自己需要的颜色变量,即可在项目中使用

原理

通过 vite-plugin-vben-theme 插件,将所有的颜色变量抽取到独立的 css 文件,并且全部在 html 上面加上 css 选择器。通过改变 html 标签的 data-theme 属性来进行夜间模式切换

配置

夜间模式颜色配置通过 vite-plugin-vben-theme 实现,具体代码在 build/vite/plugin/theme

ts
antdDarkThemePlugin({
    preloadFiles: [
        path.resolve(process.cwd(), "node_modules/ant-design-vue/dist/antd.less"),
        // path.resolve(process.cwd(), 'node_modules/ant-design-vue/dist/antd.dark.less'),
        path.resolve(process.cwd(), "src/design/index.less")
    ],
    filter: (id) => (isBuild ? !id.endsWith("antd.less") : true),
    // extractCss: false,
    darkModifyVars: {
        ...generateModifyVars(true),
        "text-color": "#c9d1d9",
        "primary-1": "rgb(255 255 255 / 8%)",
        "text-color-base": "#c9d1d9",
        "component-background": "#151515",
        "heading-color": "rgb(255 255 255 / 65%)",
        // black: '#0e1117',
        // #8b949e
        "text-color-secondary": "#8b949e",
        "border-color-base": "#303030",
        // 'border-color-split': '#30363d',
        "item-active-bg": "#111b26",
        "app-content-background": "#1e1e1e",
        "tree-node-selected-bg": "#11263c",

        "alert-success-border-color": "#274916",
        "alert-success-bg-color": "#162312",
        "alert-success-icon-color": "#49aa19",
        "alert-info-border-color": "#153450",
        "alert-info-bg-color": "#111b26",
        "alert-info-icon-color": "#177ddc",
        "alert-warning-border-color": "#594214",
        "alert-warning-bg-color": "#2b2111",
        "alert-warning-icon-color": "#d89614",
        "alert-error-border-color": "#58181c",
        "alert-error-bg-color": "#2a1215",
        "alert-error-icon-color": "#a61d24"
    }
})

切换

只需要使用 vite-plugin-vben-theme 提供的函数来进行切换即可

ts
import { darkCssIsReady, loadDarkThemeCss } from "@kirklin/vite-plugin-vben-theme/es/client";
import { addClass, hasClass, removeClass } from "/@/utils/DomUtils";

export async function updateDarkTheme(mode: string | null = "light") {
    const mainHtml = document.getElementById("mainHtml");
    if (!mainHtml) {
        return;
    }
    const hasDarkClass = hasClass(mainHtml, "dark");
    if (mode === "dark") {
        if (import.meta.env.PROD && !darkCssIsReady) {
            await loadDarkThemeCss();
        }
        mainHtml.setAttribute("data-theme", "dark");
        if (!hasDarkClass) {
            addClass(mainHtml, "dark");
        }
        return;
    }
    mainHtml.setAttribute("data-theme", "light");
    if (hasDarkClass) {
        removeClass(mainHtml, "dark");
    }
}

自定义组件实现夜间模式

自定义的组件需要增加夜间模式,可以通过在样式中增加下面的样式覆盖正常样式

vue
<style lang="less">
    [data-theme='dark'] {
    
    }
</style>