preface
Each website will have its own theme color, but with the volume of the industry, more and more websites in order to highlight the characteristics, but also to meet the needs of users more, launched the website skin function. Users can choose their own theme of the site: night theme and so on, so as to achieve personalized customization.
There are mainly 2 kinds of skin changing functions on the market:
- The site comes with a set of themes, and users can only choose from a limited number of themes.
- Theme color is changed by the user at will, truly personalized customization of the user.
1 common front-end skin changing schemes
1.1 Utilize the class namespace
Pros: Simple, easy to understand, very easy to implement.
Disadvantages: Class needs to be defined, manual maintenance, easy confusion
1.2 Preparing Multiple CSS Themes (Recommended)
Pros: Very easy to understand, one set of themes defines one set of CSS
Cons: Multiple sets of CSS style code written by hand, and changing the theme requires downloading new CSS style code.
1.3 Dynamic peels
Principle: Mainly based on the implementation of element-UI skin scheme, generate a set of theme, the theme color configuration written in JS, in the browser with JS dynamic modification style label to cover the original CSS.
Advantages: Automatic replacement in the form of defined functions, strong operability
Disadvantages: It requires a unified package of index.css, which is difficult to implement.
1.4 Less Online compilation and implementation
How it works: Implemented using the modifyVars() method, based on compilation of less in the browser. When importing less files, you need to import them in link mode, and then modify the less variable based on the method in less.js.
Features: Compile speed depends on client performance, switch is not timely, compile at runtime, need to introduce additional less-main. js, style file through link.
This approach is generally not recommended.
1.5 CSS Variable Peels (recommended)
Advantages: Only one set of CSS files; There is no delay in peels; Low browser performance requirements; Can automatically adapt to a variety of theme colors
Disadvantages: Not compatible with IE
2 Requirements to be implemented
According to the common theme skin scheme on the market, the most consistent with the user’s personalized customization scheme is undoubtedly to let the user customize the theme color, to achieve hot skin.
Final demand:
- There are several theme colors to choose from by default
- Users can also customize theme colors
- After the user selects a theme, it takes effect immediately without restarting the project or repackaging the project
3 Adopted scheme
In order to meet the above requirements, and to achieve a little more simple, we finally adopt less+ CSS variable combination to implement heat skin. Since we need a hot skin, themes provided by UI component libraries such as iView are not considered because they require a project restart after each theme change.
Preparations:
- Vue project
- Install the less
4 Concrete Implementation
4.1 Initializing the VUE Project
Initialize any Vue project, of course you can change it in an existing project:
4.2 Installing Necessary Plug-ins
Here we will use two styling plugins. The project executes the following command:
npm install style-resources-loader -D
npm install vue-cli-plugin-style-resources-loader -D
Copy the code
In order to use less in our Vue project, we also need to install less plug-ins:
NPM install [email protected] --save NPM install less --saveCopy the code
How to configure less in Vue projects is not discussed here, because our focus is not here, our ultimate goal is to be able to use less in projects.
4.3 new style. Less
Style. less is used to configure the global default style, which can also be a default theme or font color. Create a new theme folder in the project SRC directory and create style.less as follows:
/ SRC /theme/style.less // Default theme color @primarycolor: var(--primaryColor, #000); @primaryTextColor: var(--primaryTextColor, green); Export {name: "less"; primaryColor: @primaryColor; primaryTextColor: @primaryTextColor; }Copy the code
4.4 configuration vue. Config. Js
Create a vue.config.js file in the root directory of the project and write the configuration as follows:
const path = require("path"); module.exports = { pluginOptions: { "style-resources-loader": { preProcessor: "less", patterns: Path.resolve (__dirname, "./ SRC /theme/style.less"),],},},};Copy the code
Once we have configured the vue.config.js file, we can use our pre-defined less variable anywhere in the project, as shown in the following example:
<style lang="less" scoped>
p {
color: @primaryTextColor;
}
</style>
Copy the code
Let’s arbitrarily change our Vue project:
Modify the HelloWorld component to use less syntax in the component and the global variables we just defined.
The component code is as follows:
<template> <div class="hello"> <p> I am testing text </p> </div> </template> <script> export default {name: "HelloWorld",}; </script> <style scoped lang="less"> .hello { p { color: @primaryTextColor; } } </style>Copy the code
The text color is the green we just set.
4.5 Configuring Several Optional Topics
Create model.js under/SRC /theme and write a custom theme code as follows:
Export const themes = {default: {primaryColor: `${74}, ${144},${226}`, primaryTextColor: `${74}, ${144},${226}`, }, dark: { primaryColor: `${0},${0},${0}`, primaryTextColor: `${0},${0},${0}`, }, };Copy the code
Here we define two default themes so that users can switch between them. We use rGBA for theme colors because we may need to use the same theme color in different places, but with different transparency.
4.6 Write methods to modify topics
The global color variable and the two default themes have been written, and here we have implemented the statically changed theme, that is, the color can be changed to take effect when the project is re-run. But that’s not what we want, we need to change the theme dynamically, so we also need to write a method that can change the theme dynamically.
Create a new theme. Js file under the/SRC /theme folder with the following code:
import { themes } from "./model"; Const changeStyle = (obj) => {for (let key in obj) {document.getelementsByTagName ("body")[0] .style.setProperty(`--${key}`, obj[key]); }}; Export const setTheme = (themeName) => {localstorage. setItem("theme", themeName); ThemeConfig = themes[themeName] const themeConfig = themes[themeName]; If (themeConfig) {localstorage.setitem ("primaryColor", themeconfig.primarycolor); / / save the theme color to the local localStorage. SetItem (" primaryTextColor, "themeConfig. PrimaryTextColor); // Save the text color to the local changeStyle(themeConfig); } else {let themeConfig = {primaryColor: localstorage. getItem("primaryColor"), primaryTextColor: localStorage.getItem("primaryTextColor"), }; changeStyle(themeConfig); }};Copy the code
Here we write two methods, one is to change the value of the global CSS variable to change the style, the other is to change the theme of the method, we can let the user select a set of themes or custom colors.
4.7 Dynamically Changing themes
Modify our HelloWorld component to show how to dynamically modify the theme.
The test code is as follows:
<template> <div class="hello"> <div class="box-1"></div> <div class="box-2"></div> <p> I am testing text </p> <button @click="custom"> Custom theme </button> </div> </template> <script> import { setTheme } from ".. /theme/theme"; export default { name: "HelloWorld", mounted() { this.init(); }, methods: {init() {setTheme("default"); }, // Change to the default theme defaultTheme() {setTheme("default"); }, // Change to dark theme dark() {setTheme("dark"); }, // change to custom theme custom() {let newColor = {r: 12, g: 33, b: 234,}; let newPrimaryColor = `${newColor.r},${newColor.g},${newColor.b}`; localStorage.setItem("primaryColor", newPrimaryColor); // Store the new theme color into the local setTheme(); ,}}}; </script> <style scoped lang="less"> .hello { display: flex; flex-direction: column; align-items: center; .box-1 { width: 50px; height: 50px; margin-bottom: 30px; background: rgba(@primaryColor, 1); } .box-2 { width: 50px; height: 50px; margin-bottom: 30px; Background: rgba (@ primaryColor, 0.3); } p { color: @primaryTextColor; } } </style>Copy the code
When we enter the page, the default theme style will be used, and then the user can click the button to change the custom style, and it will be saved locally.
5 concludes
Using LESS and CSS variables to dynamically modify the theme, we mainly created 3 style files, the role is the default theme, several sets of custom theme and modify the theme tool function. This article is just a simple primer, usually we provide a color palette for custom themes that you can use in combination.