小程序换肤

1、需求:接手一个别人做的小程序,需要加上换肤的功能,看了网上几款换肤实现的思路,很麻烦了,工作量又大,于是自己想出这个比较好的解决方案

2、思路:利用css的属性选择器来设置不同的自定义变量,利用globalData和Behavior去实时获取主题并设置页面属性,然后在页面使用已经定义好的自定义变量就好了

3、具体实施:

3-1、设置主题

新建一个theme.wxss

[data-theme=theme1]{
  --text:blue;
  --bg:aqua;
}
[data-theme=theme2]{
  --text:red;
  --bg:pink;
}

在app.wxss引入

@import "style/theme.wxss";

在页面wxml处最外层加上data-theme属性(theme和themeSwitch会在3-2里说明)

<view class="page" data-theme="{{theme}}">
  <text>小程序换肤小程序换肤小程序换肤小程序换肤小程序换肤小程序换肤小程序换肤</text>
  <button bindtap="themeSwitch">按钮</button>
</view>

页面wxss里使用自定义变量(到了这一步并不能看到效果,因为属性还没设置上去)

.page{
  width: 100vw;
  height: 100vh;
  background-color: var(--bg);
}
text{
  color: var(--text);
}

3-2、切换主题

在app.js的globalData里新增theme变量,并在app.js引入一个名为theme的Behavior实例

// app.js
 const theme=require('utils/theme.js')
App({
  onLaunch: function () {
      this.globalData.theme=wx.getStorageSync('theme') || 'theme1'
      if (wx.getStorageSync('theme') == 'theme1') {
        wx.setNavigationBarColor({
          frontColor: "#ffffff",
          backgroundColor: "#EB2D27",
        })
      } else if (wx.getStorageSync('theme') == 'theme2') {
        wx.setNavigationBarColor({
          frontColor: "#ffffff",
          backgroundColor: "#0000FF",
        })
      }
  },
  globalData: {
    theme: 'theme1'
  },
  theme
});

theme.js设置的Behavior实例

module.exports = Behavior({
  data: {
    theme: ''
  },
  ready: function () {
    this.setData({
      theme: getApp().globalData.theme
    })
    this.setTheme()
  },
  methods: {
    themeSwitch: function () {
      if (this.data.theme == 'theme1') {
        this.setData({
          theme: "theme2"
        })
        wx.setStorageSync('theme', 'theme2')
        getApp().globalData.theme = "theme2"
        this.setTheme()
      } else if (this.data.theme == 'theme2') {
        this.setData({
          theme: "theme1"
        })
        wx.setStorageSync('theme', 'theme1')
        getApp().globalData.theme = "theme1"
        this.setTheme()
      }
    },
    setTheme: function () {
      if (this.data.theme == 'theme1') {
        wx.setNavigationBarColor({
          frontColor: "#ffffff",
          backgroundColor: "#EB2D27",
        })
      } else if (this.data.theme == 'theme2') {
        wx.setNavigationBarColor({
          frontColor: "#ffffff",
          backgroundColor: "#0000FF",
        })
      }
    }
  }
})

在页面加上behaviors: [app.theme]就大功告成

const app=getApp()
Page({
  behaviors: [app.theme],
  /**
   * 页面的初始数据
   */
  data: {
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

})

4、效果(要修改顶部之类也可以在app.theme里添加)

 

posted @ 2022-03-24 04:45  Pavetr  阅读(256)  评论(0)    收藏  举报