uniapp适配暗黑模式的实现方法

在uniapp中如何实现暗黑模式的适配?需要修改哪些配置文件和样式?有没有兼容多端的具体实现方案?

2 回复

在uniapp中实现暗黑模式,可通过CSS变量或条件类名切换主题。使用uni.setStorageSync保存主题设置,在App.vue中监听系统主题变化,动态修改全局样式。


在 UniApp 中实现暗黑模式适配,主要通过以下步骤完成:

1. 检测系统主题

使用 uni.getSystemInfo() 获取系统当前主题模式:

uni.getSystemInfo({
  success: (res) => {
    const theme = res.theme || 'light';
    this.applyTheme(theme);
  }
});

2. 监听主题变化

App.vueonLaunch 中监听系统主题变化:

// #ifdef APP-PLUS
plus.navigator.subscribe('uistylechange', (result) => {
  this.applyTheme(result.style);
});
// #endif

3. 应用主题样式

定义 CSS 变量或类名切换:

/* 定义浅色/深色主题变量 */
:root {
  --bg-color: #ffffff;
  --text-color: #333333;
}

[data-theme="dark"] {
  --bg-color: #1a1a1a;
  --text-color: #ffffff;
}

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

4. 动态切换类名

在 Vue 中根据主题动态更新:

methods: {
  applyTheme(theme) {
    const html = document.documentElement;
    html.setAttribute('data-theme', theme);
    // 或使用 uni.setStorage 保存主题选择
  }
}

5. 注意事项

  • H5/小程序:需自行实现主题切换逻辑,可使用本地存储记录用户选择
  • 组件库:如使用 uView 等支持暗黑的组件库,需按文档配置
  • 图片适配:可为深色模式准备不同图片资源

完整示例代码:

<script>
export default {
  onLaunch() {
    // 检测初始主题
    uni.getSystemInfo({
      success: (res) => {
        this.applyTheme(res.theme);
      }
    });
    
    // 监听主题变化(仅APP)
    // #ifdef APP-PLUS
    plus.navigator.subscribe('uistylechange', (result) => {
      this.applyTheme(result.style);
    });
    // #endif
  },
  methods: {
    applyTheme(theme) {
      const html = document.documentElement;
      html.setAttribute('data-theme', theme === 'dark' ? 'dark' : 'light');
    }
  }
}
</script>

通过以上方法,即可在 UniApp 中实现跨端的暗黑模式适配,兼顾系统主题与用户自定义选择。

回到顶部