首页在utils文件夹中创建theme文件夹,
theme文件夹包含三个文件【具体格式看自己如何定义数据】;
我这里创建了两个主题,每个主题用一个文件装,
【blue.ts、red.ts、index.ts】
blue文件
export const blue = {
baacgroundColor: "#f20",
};
red文件
export const red = {
baacgroundColor: "#f20",
};
index文件
import {red} from './red'
import {blue} from './blue'
export const theme = new Map<string, any>()
theme.set('red', red)
theme.set('blue', blue)
然后在app.ts文件中
import { theme } from "./utils/theme/index";
App<IAppOption>({
globalData: {
theme,//我们配置的主题数据
themeCode: "",//当前选择的主题coe
themeMap: new Map<string, any>(),//当前选择主题的map数据结构
},
onLaunch() {
//初始化默认主题
this.globalData.themeCode = "red";
wx.setStorageSync("themeCode", this.globalData.themeCode);
const defaultTheme = this.globalData.theme.get(this.globalData.themeCode);
for (const key in defaultTheme) {
this.globalData.themeMap.set(key, defaultTheme[key]);
}
},
});
使用主题
var app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
bgColor: "",
},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
//默认主题配置
this.setStyleDataByCity();
},
//点击切换主题
changeTheme() {
//获取主题code,没有默认red
const themeCode = app.globalData.themeCode === "red" ? "blue" : "red";
app.globalData.themeCode = themeCode;
wx.setStorageSync("themeCode", themeCode);
const theme = app.globalData.theme.get(themeCode);
for (const key in theme) {
app.globalData.themeMap.set(key, theme[key]);
}
//更新当前主题
this.setStyleDataByCity();
},
setStyleDataByCity() {
this.setData({
bgColor: app.globalData.themeMap.get("baacgroundColor"),
});
},
});
收工