this下添加setTheme方法,动态修改主题颜色
发布于 4 年前 作者 wluo 2425 次浏览 来自 分享

思路

修改Page中的onLoad,在this中添加方法setTheme 在页面onLoad的时候自动运行一次设置活动主题色。当页面触发事件的时候也可以通过this.setTheme(theme_id)来设置活动主题色。好比写一个类似官方this.setData 一样的方法用作设置主题颜色变量(当前只能通过style设置页面的) 这里感谢o0o有脾气的酸奶提供了思路

上代码

  1. themeList.js (颜色变量配置文件)
//注意给默认主题的active为true,且每个颜色变量的后面要加分号。
    export const themeList = [
      {
        id:'green',
        name:'绿油油',
        active:true,
        color:`
        --theme:#18b357;
        --white: #f5f5f5;
        --red: red;
        --gray: #eee;
        --darkgray: #aaa;
        --black: #666; 
        `
      },
      {
        id:'skyblue',
        name:'天空蓝',
        active:false,
        color:` 
        --theme:skyblue;
        --white: #f5f5f5;
        --red: #f40;
        --gray: #aaa;
        --darkgray: #666;
        --black: #333;
        `
      }
    ]
  1. main.wxss (主样式文件,在app.wxss内被引入)
    /* main.wxss */
     .bg-theme{
     background-color:var(--theme,white)
     }
     .color-red(
     color:var(--red,#f40)
     )
     .color-white{
     color:var(--white,#f5f5f5)
     }  
   /* app.wxss */
     @import './style/main.wxss'
  1. setTheme. js
import { themeList } from '../config/themeList'
const myPage = Page //保留原始Page
Page = function (e) { //重新定义Page e是传进来的对象this
    let { onLoad } = e //保存原始e.onLoad
    e.setTheme = function (theme_id = null) {//添加一个默认方法
        if (theme_id !== null && typeof theme_id !== 'string') {
            throw `${theme_id} must be an string type`
        }
        const activeTheme = themeList.find(ele => ele.active)
        if (theme_id === null) {
            this.setData({
                themeColor: activeTheme.color
            })
        } else {
            activeTheme.active = false;
            const currentTheme = themeList.find(ele => ele.id === theme_id)
            currentTheme.active = true
            this.setData({
                themeColor: currentTheme.color
            })
        }
    }
    e.onLoad = function (options) {//重新定义e.onload 
        this.setTheme()//自动运行默认主题
        onLoad && onLoad.call(this, options) //再运行原始onload
    }
    return myPage.call(this, e)//最终还是运行原来的Page
}
  1. app.js引入
  //app.js
  import './utils/setTheme'
  App({
    onLaunch: function () {
    },
    globalData: {
    }
  })
  1. index.js
Page({
  data: {
  },
  changeTheme(){
  //更改主题事件可以直接调用setTheme函数
  this.setTheme('skyblue')
  },
  onLoad: function () {
  }
})

  1. 代码片段[https://developers.weixin.qq.com/s/ciE52cm57BkF]

总结

由于无法动态设置app.wxss的变量,只能采取动态设置每个Page的最外层style,所以采取在Page的onLoad的时候自动设置themeColor,为了让优雅调用设置主题,直接把setTheme函数写入到this中去,达到方便调用的目的 。

缺点是

  1. 必须在每个页面的wxml最外层加上style="{{themeColor}}"
  2. 页面必须运行onload才能重新加载主题
1 回复

这思路不错,学习一下。

回到顶部