uniapp H5、APP动态配置系统色

783 阅读1分钟

一、动态配置系统色

1、先新建一个系统色的theme.js配置文件

const themeList = {
    green: '--view-theme: rgba(66,202,77,1);--view-fontColor:#fff;',
    red: '--view-theme: rgba(233,51,35,1);--view-fontColor:#333'
}

export default themeList

2、在App.vue页面将配置信息进行存储

import themeList from 'theme';
import colors from '@/mixins/color.js';

export default {
    mixins: [colors],
    onLaunch(){
        uni.setStorageSync('themeList', themeList.red);
        uni.$emit('ok', themeList.red);
    }
}

minxins color.js

export default {
    data() {
        return {
            themeList: ''
        };
    },
    created() {
        this.themeList = uni.getStorageSync('themeList')
        uni.$on('ok', (data) => {
            this.themeList = data
        })
    }
};

3、创建.scss文件

/* 界面主题色 */
.theme-bg {
    background: var(--view-theme) !important
}

/* 字体主题色 */
.font-color {
    color: var(--view-fontColor) !important
}

uni.scss

$theme-bg:var(--view-theme);
$font-color:var(--view-fontColor);

4、使用

main.js全局注入

import colors from '@/mixins/color.js';
Vue.mixin(colors);

App.vue全局设置背景色

page {
    width: 100%;
    height: 100%;
    background: $theme-bg;
}

页面:

<template>
    // 在根节点加载系统色样式
    <page-meta :page-style="themeList"></page-meta> 
    <view>
       <view class="home font-color">xxx</view>
    </view>
</template>

<style lang="scss">
    .home{
        background: $theme-bg;
    }
</style>

bug: H5端 page-meta组件 属性page-style偶尔失效

问题同:ask.dcloud.net.cn/question/10…

<template>
    <view class="content-bg-color" :style="themeColor">
        // 解决page-meta中page-style失效问题
        xxx
    </view>
</template>

<style lang="scss>
// 由于系统色样式未在根节点加载,无法设置全局背景色,通过class去改背景色
.content-bg-color{
    width: 100%;
    height: 100vh;
    background-color: $theme-bg;
    overflow: hidden;
}
</style>
注意:需要在每个页面都绑定样式

二、静态设置根节点样式

App.vue

/* 全局样式应用到根节点 */

:root {
    --primary-color: #ff0000; /* 自定义主题颜色 */
}

uni.scss

$theme-bg:var(--primary-color);

或者 uni.scss

$theme-bg: #ff0000;