More articles
preface
Now that the UI library is set up, it’s time to make components. Here’s a component library that dynamically changes the element- UI color
Analysis of the
Element-ui provides a way to change the theme (there’s a lot on the web that I won’t go into here) by changing the SCSS variable, but this is static, which means you need to do all of this before the code runs. Once the project is started, we load the compiled and compressed CSS file. If you want to change the theme dynamically, it is common to generate a new style and then add a new style tag to the DOM, overwriting the previous style
implementation
Receives a defaultColor parameter that initializes the theme color
props: {
defaultColor: {
type: String}}Copy the code
To ensure that the CSS version of Element-UI is correct, we read the version from element-ui/package.json
const version = require("element-ui/package.json").version; / / version number
const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`;
Copy the code
Even accessing the CDN can still have network problems, so we also accept dynamic incoming urls
// Access CDN resources by default
props: {
url: {
type: String.default: url
}
}
Copy the code
Even if the theme is changed dynamically, the color will be reset after refreshing, so we receive an isCache parameter to decide whether to cache or not. The cache scheme is localStorage
// No cache by default
props: {
isCache: {
type: Boolean.default: false,}}Copy the code
The next major logic (look at the code) :
- call
getThemeCluster
Get old and new cleft colors - First entry to judgment
this.chalk
Whether the stylesheet content has been cached, or notgetCSSString
Method to get the style - call
updateStyle
Update and get the latest stylesheet content - Determine whether there is
id
forchalk-style
thestyle
If it does not, it generates, and if it does, it assigns the latest stylesheet and joinsDOM
The complete code
<template> <el-color-picker :size="size" v-model="theme" class="theme-picker" @change="onChange" :predefine="predefineColors" popper-class="theme-picker-dropdown" > </el-color-picker> </template> <script> const version = require("element-ui/package.json").version; / / version number const url = {version} / lib/theme ` https://unpkg.com/element-ui@$- chalk/index. CSS `; const ORIGINAL_THEME = "#409EFF"; export default { name: "QjdTheme", data() { return { chalk: "", theme: "", predefineColors: Object.freeze([ "#409EFF", "#ff4500", "#ff8c00", "#ffd700", "#90ee90", "#00ced1", "#1e90ff", "#c71585", "rgba(255, 69, 0, 0.68), "" RGB (255, 120, 0)", "HSV (51, 100, 98)," "hsva (120, 40, 94, 0.5)", "an HSL (181, 100%, 37%)," "hsla (209. 100%, ", "#c7158577",]),}; }, props: { size: { type: String, default() { return ""; }, }, defaultColor: { type: String, }, isCache: { type: Boolean, default: false, }, url: { type: String, default: url } }, mounted() { const colorPicker = localStorage.getItem("colorPicker"); const { defaultColor } = this; Localstorage.getitem ("colorPicker") > defaultColor > ORIGINAL_THEME this.theme = this.CheckIsColor(colorPicker) ? colorPicker : this.CheckIsColor(defaultColor) ? defaultColor : ORIGINAL_THEME; }, watch: { theme(val) { if (typeof val ! == "string" || ! val) return; this.isCache && localStorage.setItem("colorPicker", val); const themeCluster = this.getThemeCluster(val.replace("#", "")); const originalCluster = this.getThemeCluster( ORIGINAL_THEME.replace("#", "") ); const getHandler = (variable, id) => { return () => { const newStyle = this.updateStyle( this[variable], originalCluster, themeCluster ); let styleTag = document.getElementById(id); // Check if there is already a tag, if there is, generate if (! styleTag) { styleTag = document.createElement("style"); styleTag.setAttribute("id", id); document.head.appendChild(styleTag); } // replace with a newStyle sheet styletag. innerText = newStyle; }; }; const chalkHandler = getHandler("chalk", "chalk-style"); If (! this.chalk) { this.getCSSString(this.url, chalkHandler, "chalk"); } else { chalkHandler(); }},}, methods: {clearCache() {localstorage.removeitem ("colorPicker"); }, // Color change onChange(e) {if (e) {this.theme = e; }}, / / determine whether to color CheckIsColor (bgVal) {if (bgVal) {var type = "^ # [0-9 a - fA - F] {6} $"; var re = new RegExp(type); if (bgVal.match(re) == null) { type = "^[rR][gG][Bb][(]([\\s]*(2[0-4][0-9]|25[0-5]|[01]? [0-9] [0-9]?) [\\s]*,){2}[\\s]*(2[0-4]\\d|25[0-5]|[01]? \\d\\d?) [\\s]*[)]{1}$"; re = new RegExp(type); if (bgVal.match(re) == null) { return false; } else { return true; } } else { return true; }}, // updateStyle(style, oldCluster, newCluster) {let newStyle = style; oldCluster.forEach((color, index) => { newStyle = newStyle.replace(new RegExp(color, "ig"), newCluster[index]); }); return newStyle; }, // get the default theme style when initializing and copy it to this.chalk getCSSString(URL, callback, variable) {const XHR = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status === 200) { this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, ""); callback(); }}; xhr.open("GET", url); xhr.send(); }, // Get a series of colors // GetThemeCluster (theme) {const tintColor = (color, tint) => {let red = parseInt(color.slice(0, 2), 16); let green = parseInt(color.slice(2, 4), 16); let blue = parseInt(color.slice(4, 6), 16); if (tint === 0) { return [red, green, blue].join(","); } else { red += Math.round(tint * (255 - red)); green += Math.round(tint * (255 - green)); blue += Math.round(tint * (255 - blue)); red = red.toString(16); green = green.toString(16); blue = blue.toString(16); return `#${red}${green}${blue}`; }}; const shadeColor = (color, shade) => { let red = parseInt(color.slice(0, 2), 16); let green = parseInt(color.slice(2, 4), 16); let blue = parseInt(color.slice(4, 6), 16); red = Math.round((1 - shade) * red); green = Math.round((1 - shade) * green); blue = Math.round((1 - shade) * blue); red = red.toString(16); green = green.toString(16); blue = blue.toString(16); return `#${red}${green}${blue}`; }; const clusters = [theme]; for (let i = 0; i <= 9; i++) { clusters.push(tintColor(theme, Number((i / 10).toFixed(2)))); } clusters. Push (shadeColor theme, (0.1)); return clusters; ,}}}; </script>Copy the code
API
Attributes
parameter | instructions | type | An optional value | The default value |
---|---|---|---|---|
defaultColor | The default theme | String | – | – |
size | The size | String | Medium, small, mini | – |
isCache | Enable cache | Boolean | – | false |
url | Loading resource address | String | – | unpkg.com/element-ui@… |
Methods
The method name | instructions | parameter |
---|---|---|
clearCache | Clear the cache | – |
conclusion
good good study!!!