uniapp 组件如何实现暗黑模式

在uniapp中,如何为组件实现暗黑模式?需要手动处理样式还是uniapp有内置的解决方案?具体应该如何操作?

2 回复

在uni-app中实现暗黑模式,可以通过以下步骤:

  1. 使用CSS变量定义主题色,例如:
:root {
  --bg-color: #fff;
  --text-color: #333;
}
[data-theme="dark"] {
  --bg-color: #333;
  --text-color: #fff;
}
  1. 在页面中动态切换data-theme属性,通过JavaScript修改document.documentElementdataset.theme

  2. 结合uni.setStorageSync保存用户选择的主题,确保下次打开应用时保持主题设置。


在 UniApp 中实现暗黑模式,可以通过以下步骤完成:

1. 使用 CSS 变量和媒体查询

  • 定义全局 CSS 变量,根据系统主题切换颜色值。
  • App.vue<style> 中设置媒体查询,检测系统暗黑模式。

示例代码(App.vue):

:root {
  --bg-color: #ffffff;
  --text-color: #333333;
}

[@media](/user/media) (prefers-color-scheme: dark) {
  :root {
    --bg-color: #1e1e1e;
    --text-color: #ffffff;
  }
}

page {
  background-color: var(--bg-color);
  color: var(--text-color);
}

2. 动态类名切换

  • 通过 JavaScript 动态添加/移除暗黑模式的类名,手动控制主题切换。
  • 结合 Vue 的响应式数据管理主题状态。

示例代码:

<template>
  <view :class="isDark ? 'dark-theme' : 'light-theme'">
    <text>当前主题:{{ isDark ? '暗黑' : '明亮' }}</text>
    <button @click="toggleTheme">切换主题</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isDark: false
    };
  },
  methods: {
    toggleTheme() {
      this.isDark = !this.isDark;
    }
  }
};
</script>

<style>
.light-theme {
  background-color: #ffffff;
  color: #333333;
}
.dark-theme {
  background-color: #1e1e1e;
  color: #ffffff;
}
</style>

3. 全局状态管理(Vuex)

  • 使用 Vuex 存储主题状态,确保所有页面同步切换。
  • uni.scss 中定义主题变量,便于统一管理。

步骤:

  1. 在 Vuex 中定义 theme 状态和 toggleTheme 方法。
  2. 各页面通过 mapStatemapMutations 获取和切换主题。
  3. uni.scss 中通过 SCSS 变量定义主题色,根据 Vuex 状态动态应用。

4. 持久化存储

  • 使用 uni.setStorageSync 保存用户选择的主题,应用启动时恢复设置。

示例代码:

// 在 App.vue 的 onLaunch 中读取存储的主题
export default {
  onLaunch() {
    const savedTheme = uni.getStorageSync('theme');
    if (savedTheme) {
      this.$store.commit('setTheme', savedTheme);
    }
  }
};

// 切换主题时保存
toggleTheme() {
  this.isDark = !this.isDark;
  uni.setStorageSync('theme', this.isDark ? 'dark' : 'light');
}

注意事项:

  • 兼容性:媒体查询 prefers-color-scheme 在部分低版本系统或小程序中可能不支持,需测试目标平台。
  • 性能:避免频繁操作 DOM 或存储,影响应用流畅度。

通过以上方法,可以灵活实现 UniApp 的暗黑模式,支持系统自动检测和手动切换。

回到顶部