在小程序中如何使用主题配置文件

首页在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"),
    });
  },
});

收工

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值