uni-app切换主题色

1,468 阅读1分钟

app有深浅两套主题色,给uni-app加个主题切换的机制, 未要求动态切换。

随主题色改变的有字体颜色、背景图片等,

通过scss的变量来定义两套主题色。

实现:

1、 根目录创建config.js
// 主题色  dark || light
const theme = 'dark';
module.exports = {
	theme,
};
2、根目录创建vue.config.js(webpack语法)
const config  = require('./config.js')

module.exports = {
  css: {
    loaderOptions: {
	  // 低版本  additionalData  高版本 prependData (在 sass-loader v8 中)
          // 向预处理器loader传入共享的全局变量
      scss: {
        prependData: `
            @import "~@/common/theme/${config.theme}/variables.scss";
            `
      },
    }
  },	
}


3、 新建文件 /common/theme/${theme}/variables.scss 存放全局样式变量
4、App.vue中 引入theme, 放至globalData,全局使用
import { theme } from '@/config.js'
     globalData: {  
            theme: theme
    },

如果要求 动态切换主题的话 可以使用 vuex +css变量 绑定到组件根元素上来实现