在线主题切换不同于主题定制,用户可以在页面上点击手动切换主题,主要是颜色和图片的切换,而不是在项目中通过修改某些变量值,打包生成不同主题的包给不同的用户使用。
实现方法有:定义 theme 变量,通过 prop 传递给组件,组件内部动态切换 class 或者修改 style;打包生成不同的 css 文件;浏览器直接运行 less,动态编译颜色变量;给 css 选择器加一个样式名的类选择器,并把这个类名绑定到body元素上。
在 vue 项目中使用 Less 来实现。首先给主题设置名字,新建一个 variable.less 文件,把主题名称存在变量里,然后声明主题对应的值,例如字体色、背景色。在 js 中需要到主题名,需要先在 less 文件中导出。CSS Module 有一个 :export 关键字,它在功能上等同于 ES6 的关键字 export,即导出一个 js 对象。
// src/assets/styles/variable.less@themeNames: 'light', 'dark';/* light */@font-color-light: #000;@bg-color-light: #fff;/* dark */@font-color-dark: #bdc1c5;@bg-color-dark: #202224;:export {themeNames: @themeNames;}
为了在组件中可以拿到这些 less 变量,不用每次引入,可以用 style-resources-loader 。先安装插件,再配置需要注入的 less 文件路径。
$ vue add style-resources-loader
// vue.config.jsconst path = require('path');module.exports = {pluginOptions: {'style-resources-loader': {preProcessor: 'less',patterns: [path.resolve(__dirname, './src/assets/style/index.less')]}}};
先新建一个切换主题功能的组件,获取到 variable.less 文件中声明的主题名称,作为可选项,把选择后的值存在 vuex 里,如果要保证刷新页面后主题不变,可存一份在 localStorage,初始化组件时先获取。
<template><div class="theme-tab"><label v-for="name in themeNames" :key="name"><input type="radio" :value="name" v-model="value"><span>{{ name }}</span></label></div></template><script>import lessVariable from '@/assets/style/variable.less';export default {name: 'ThemeTab',data() {const themeNames = lessVariable.themeNames.replace(/'|\s/g, '').split(',');return {themeNames,value: ''};},computed: {themeName() {return this.$store.state.themeName;}},created() {this.value = this.themeNames[0]},watch: {value() {this.$store.commit('changeTheme', this.value);}}};</script><style scoped lang="less">.theme-tab {margin: 20px 0;}</style>
方法一示例:
<template><div :class="['content-com', themeName]"><p>We all love how Vue is very easy to pick up and makes building small to medium scale applications a breeze</p></div></template><script>export default {name: 'ContentCom',data() {return {};},computed: {themeName() {return this.$store.state.themeName;}}};</script><style scoped lang="less">.content-com {padding: 20px;&.light {background: @bg-color-light;color: @font-color-light;}&.dark {background: @bg-color-dark;color: @font-color-dark;}}</style>
给 css 选择器加上统一的类名是比较方便的做法,配合 less 的 Parametric Mixins 写起来更简洁。
