需求:
因为iosapp 要求适配暗黑模式,APP内嵌H5页面也需要相应的暗黑适配,做到根据进入页面时app参数,或者页面内一键切换主题风格
解决方案
已首次进入H5时接收APP传参判断,主题风格 (暗黑模式,正常模式,)为例
在app.vue onLaunch 中加入判断
if (this.user && this.user.dark === '1') {
Vue.prototype.datatheme = 'dark'
window.document.documentElement.setAttribute('data-theme', 'dark')
} else {
Vue.prototype.datatheme = 'light'
window.document.documentElement.setAttribute('data-theme', 'light')
}
在app.vue 底部引入base.scss
<style lang="scss">
@import "styles/base.scss";
</style>
$themes: (
light: (
white: #fff,
black: #27292d,
// 主色调1
main-one: #00A54F,
// 主色调2
main-two: #1B88EE
),
dark: (
white: #27292d,
black: #fff,
// 主色调1
main-one: #00A54F,
// 主色调2
main-two: #1B88EE
)
)
@import "./_themes.scss"; // 引入_themes.scss
//遍历主题map
@mixin themeify {
@each $theme-name,
$theme-map in $themes {
//!global 把局部变量强升为全局变量
$theme-map: $theme-map !global;
//这步是判断html的data-theme的属性值 #{}是sass的插值表达式
//& sass嵌套里的父容器标识 @content是混合器插槽,像vue的slot
[data-theme="#{$theme-name}"] & {
@content;
}
}
}
//声明一个根据Key获取颜色的function
@function themed($key) {
@return map-get($theme-map, $key);
}
//获取背景透明度
@mixin background($color) {
@include themeify {
background: themed($color)
}
}
@mixin background_imp($color) {
@include themeify {
background: themed($color) !important
}
}
//获取背景颜色
@mixin background_color($color) {
@include themeify {
background-color: themed($color)
}
}
@mixin background_color_imp($color) {
@include themeify {
background-color: themed($color) !important
}
}
//获取字体颜色
@mixin font_color($color) {
@include themeify {
color: themed($color);
}
}
@mixin font_color_imp($color) {
@include themeify {
color: themed($color) !important
}
}
//获取边框颜色
@mixin border_color($color) {
@include themeify {
border-color: themed($color)
}
}
@mixin border_color_imp($color) {
@include themeify {
border-color: themed($color) !important
}
}
注; 方式创建了两种, 考虑到 !important,自己按需使用
// 字体颜色
.color-white {
@include font_color_imp("white")
}
.color-black {
@include font_color_imp("black")
}
// 边框颜色
.line-color {
@include border_color("divider")
}
// 背景颜色
.bg-black {
@include background_color_imp("black")
}
.bg-white {
@include background_color_imp("white")
}
以上即为vue切换主题风格的实现原理
在app.vue中已经全局定义了变量 datatheme (Vue.prototype.datatheme = ‘dark’)
页面中只需 使用 this.datatheme 即可取到风格参数
:background="datatheme === 'light' ? '#fff' : '#27292d'"
定义全局方法,进入页面后设置头部导航栏字体颜色及背景颜色
function setNavigation () {
if (store.getters.user.dark === '0') {
uni.setNavigationBarColor({
frontColor: '#000000',
backgroundColor: '#ffffff'
})
} else {
uni.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: '#27292d'
})
}
}