Skip to content
iuiDesign
100%
02:32
本页目录

组件库提供了暗色模式,以适配在操作系统暗色模式下的展示体验。
可以点击右上角开关切换整体浅色与暗色模式体验。

如何使用

跟随系统暗色模式

uni-app 文档:DarkMode 适配

  1. 在根目录创建 theme.json,并配置颜色变量。
json
// theme.json
// 用于颜色主题相关的变量定义,需要先在 themeLocation 中配置 theme.json 的路径
{
  // 浅色模式
  "light": {
    "navBgColor": "#f8f8f8",
    "navTxtStyle": "black"
  },
  // 暗色模式
  "dark": {
    "navBgColor": "#292929",
    "navTxtStyle": "white"
  }
}
// theme.json
// 用于颜色主题相关的变量定义,需要先在 themeLocation 中配置 theme.json 的路径
{
  // 浅色模式
  "light": {
    "navBgColor": "#f8f8f8",
    "navTxtStyle": "black"
  },
  // 暗色模式
  "dark": {
    "navBgColor": "#292929",
    "navTxtStyle": "white"
  }
}

完成定义后,可在 pages.json 中全局配置或页面配置的相关属性中以 @ 开头引用:

json
// 全局配置
{
  "globalStyle": {
    "navigationBarBackgroundColor": "@navBgColor",
    "navigationBarTextStyle": "@navTxtStyle"
  }
}
// 页面配置
{
	"path": "pages/index/index",
	"style":{
		"navigationBarBackgroundColor": "@navBgColor",
		"navigationBarTextStyle": "@navTxtStyle"
	}
}
// 全局配置
{
  "globalStyle": {
    "navigationBarBackgroundColor": "@navBgColor",
    "navigationBarTextStyle": "@navTxtStyle"
  }
}
// 页面配置
{
	"path": "pages/index/index",
	"style":{
		"navigationBarBackgroundColor": "@navBgColor",
		"navigationBarTextStyle": "@navTxtStyle"
	}
}
  1. manifest.json 中配置 darkmodetrue
json
// manifest.json
{
  // ...

  // 微信小程序
  "mp-weixin": {
    "darkmode": true,
    "themeLocation": "theme.json" // 如果 theme.json 在根目录可省略
  },

  // ...

  // H5
  "h5": {
    "darkmode": true,
    "themeLocation": "theme.json" // 如果 theme.json 在根目录可省略
  }
}
// manifest.json
{
  // ...

  // 微信小程序
  "mp-weixin": {
    "darkmode": true,
    "themeLocation": "theme.json" // 如果 theme.json 在根目录可省略
  },

  // ...

  // H5
  "h5": {
    "darkmode": true,
    "themeLocation": "theme.json" // 如果 theme.json 在根目录可省略
  }
}

完成以上配置后,即可在微信小程序和 H5 中实现跟随系统暗色模式。

手动切换暗色模式 仅 H5

html
<template>
  <iui-switch v-model="darkmode" @change="onChange" />
</template>

<script setup>
  import { ref, computed } from "vue";
  const darkmode = ref(false);

  const onChange = () => {
    if (darkmode.value) {
      // 切换到暗色模式
      document.documentElement.setAttribute("class", "dark");
    } else {
      // 切换到浅色模式
      document.documentElement.removeAttribute("class");
    }
  };
</script>
<template>
  <iui-switch v-model="darkmode" @change="onChange" />
</template>

<script setup>
  import { ref, computed } from "vue";
  const darkmode = ref(false);

  const onChange = () => {
    if (darkmode.value) {
      // 切换到暗色模式
      document.documentElement.setAttribute("class", "dark");
    } else {
      // 切换到浅色模式
      document.documentElement.removeAttribute("class");
    }
  };
</script>

实现原理

iui Design 使用 CSS 变量 来构建的暗黑主题。组件内部内置了两套色板,一套默认的亮色,另外一套是根据主题色自动生成的暗色色板。