ElementUI主题颜色动态切换并缓存

今天给大家分享一下在Vue中使用ElementUI时,想切换主题颜色的两种方式。

第一种:静态改变项目中的主题颜色

比较简单,稍微带过:
项目中创建element-variables.scss文件,编写内容:

/* 改变主题色变量 */
$--color-primary: teal;/* 改变 icon 字体路径变量,必需 */
$--font-path: '~element-ui/lib/theme-chalk/fonts';@import "~element-ui/packages/theme-chalk/src/index";

之后,在项目的入口文件中,直接引入以上样式文件即可(无需引入 Element 编译好的 CSS 文件)

import Vue from 'vue'
import Element from 'element-ui'
import './element-variables.scss'Vue.use(Element)

第二种:重点!!!动态切换主题颜色并做缓存

  1. 创建theme.js文件,作为工具类,并写入以下内容:
const __DEFUALT__COLOR = "#409EFF"
const version = require('element-ui/package.json').versionclass Theme {constructor() {const color = this._getLocalTheme() || __DEFUALT__COLOR;const oldVal = this._getLocalTheme() || __DEFUALT__COLOR;this.changeTheme(color, oldVal);this.chalk = ''}async changeTheme($color, oldVal) {const themeCluster = this._getThemeCluster($color.replace('#', ''))const originalCluster = this._getThemeCluster(oldVal.replace('#', ''))const getHandler = (id) => {return () => {const originalCluster = this._getThemeCluster(__DEFUALT__COLOR.replace('#', ''))const newStyle = this._updateStyle(this.chalk, originalCluster, themeCluster)let styleTag = document.getElementById(id)if (!styleTag) {styleTag = document.createElement('style')styleTag.setAttribute('id', id)document.head.appendChild(styleTag)}styleTag.innerText = newStyle}}if (!this.chalk) {const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`await this._getCSSString(url, 'chalk')}const chalkHandler = getHandler('chalk-style')chalkHandler()const styles = [].slice.call(document.querySelectorAll('style')).filter(style => {const text = style.innerTextreturn new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)})styles.forEach(style => {const { innerText } = styleif (typeof innerText !== 'string') returnstyle.innerText = this._updateStyle(innerText, originalCluster, themeCluster)})this._setLocalTheme("--primary-color", $color)}_getLocalTheme(key = "--primary-color") {return key && localStorage.getItem(key);}_setLocalTheme(key, value) {localStorage[key] = value;}_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) { // when primary color is in its rgb spacereturn [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}_updateStyle(style, oldCluster, newCluster) {let newStyle = styleoldCluster.forEach((color, index) => {newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])})return newStyle}_getCSSString(url) {return new Promise(resolve => {const xhr = new XMLHttpRequest()xhr.onreadystatechange = () => {if (xhr.readyState === 4 && xhr.status === 200) {this.chalk = xhr.responseText.replace(/@font-face{[^}]+}/, '')resolve()}}xhr.open('GET', url)xhr.send()})}
}export default Theme
  1. 然后在项目入口main.js中引入即可
import Vue from 'vue'
import Theme from "./utils/theme
Vue.prototype.$theme = new Theme()
  1. 在ThemePicker中使用
<template><el-color-pickerv-model="theme":predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"class="theme-picker"popper-class="theme-picker-dropdown"/>
</template><script>export default {data() {return {theme: ''}},computed: {defaultTheme() {return this.$store.state.settings.theme}},watch: {defaultTheme: {handler: function(val, oldVal) {this.theme = val},immediate: true},theme(val, oldVal) {this.$theme.changeTheme(val, oldVal)this.$store.dispatch('settings/changeSetting', {key: 'theme',value: val})}}
}
</script><style>
.theme-message,
.theme-picker-dropdown {z-index: 99999 !important;
}.theme-picker .el-color-picker__trigger {height: 26px !important;width: 26px !important;padding: 2px;
}.theme-picker-dropdown .el-color-dropdown__link-btn {display: none;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/27209.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构 | 二叉树的应用

目录 一、解析树 二、树的遍历 一、解析树 我们可以用解析树来表示现实世界中像句子或数学表达式这样的构造。 我们可以将((73)*(5-2))这样的数学表达式表示成解析树。这是完全括号表达式&#xff0c;乘法的优先级高于加法和减法&#xff0c;但因为有括号&#xff0c;所以在…

ffmpeg下载安装教程

ffmpeg官网下载地址https://ffmpeg.org/download.html 这里以windows为例,鼠标悬浮到windows图标上,再点击 Windows builds from gyan.dev 或者直接打开 https://www.gyan.dev/ffmpeg/builds/ 下载根据个人需要下载对应版本 解压下载的文件,并复制bin所在目录 新打开一个命令…

嵌入式面试3

1.线程与进程的区别和联系? 线程是否具有相同的堆栈? dll是否有独立的堆栈? 进程是死的&#xff0c;只是一些资源的集合&#xff0c;真正的程序执行都是线程来完成的&#xff0c;程序启动的时候操作系统就帮你创建了一个主线程。 每个线程有自己的堆栈。 DLL中有没有独立的…

P2340 [USACO03FALL] Cow Exhibition G

P2340 [USACO03FALL] Cow Exhibition G 很典型的背包问题。要求 IQ 与 EQ 和的最大值&#xff0c;并保证 IQ EQ 和均大于 0&#xff0c;易知 dp&#xff0c;IQ 和 EQ 均大于 0 的条件可先不管&#xff0c;最后在合法区间统计答案即可。 考虑如何求 IQ 与 EQ 和的最大值&#x…

基于YOLOv7开发构建MSTAR雷达影像目标检测系统

MSTAR&#xff08;Moving and Stationary Target Acquisition and Recognition&#xff09;数据集是一个基于合成孔径雷达&#xff08;Synthetic Aperture Radar&#xff0c;SAR&#xff09;图像的目标检测和识别数据集。它是针对目标检测、机器学习和模式识别算法的研究和评估…

前端面试题-高频考点

1 typeof类型判断 typeof 是否能正确判断类型&#xff1f; instanceof 能正确判断对象的原理是什么typeof 对于原始类型来说&#xff0c;除了 null 都可以显示正确的类型 typeof 1 // number typeof 1 // string typeof undefined // undefined typeof true // boolean typeo…

手把手写深度学习(20):搭建LLM大语言模型的敏感词过滤系统

前言:随着Llama 2、通义千问7B等越来越多的大语言模型开源,开发者们可以基于这些开源的模型搭建自己的对话系统、Agent等。但是因为我们的国情,需要开发者对这些模型进行一些特殊的“安全性”考虑,保证与用户的交互不会出现“有害信息”。这篇博客手把手教大家搭建一个大语…

Camunda 7.x 系列【6】Spring Boot 集成 Camunda 7.19

有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 2.7.9 本系列Camunda 版本 7.19.0 源码地址:https://gitee.com/pearl-organization/camunda-study-demo 文章目录 1. 前言2. Camunda Platform Run3. Spring Boot 版本兼容性4. 集成 Spring Boot5. 启动项目…

【Vue3】动态组件

动态组件的基本使用 动态组件&#xff08;Dynamic Components&#xff09;是一种在 Vue 中根据条件或用户输入来动态渲染不同组件的技术。 在 Vue 中使用动态组件&#xff0c;可以使用 元素&#xff0c;并通过 is 特性绑定一个组件的名称或组件对象。通过在父组件中改变 is 特…

vue 图片base64转化

import html2canvas from ‘html2canvas’ html2canvas(canvasDom, options).then(canvas > { //此时的图片是base64格式的&#xff0c;我们将图片格式转换一下 let type ‘png’; let imgData canvas.toDataURL(type); // 照片格式处理 let _fixType function(type) { …

2023牛客暑期多校训练营4

Bobo String Construction 结论&#xff0c;字符串哈希 Election of the King 二分查找 Merge the squares! 递归模拟&#xff0c;辗转相除法 Quest-ce Que Cest? DP&#xff0c;前缀和优化 We are the Lights 思维&#xff0c;倒推 猜测是&#xff0c;把n个字符全填0或者1是最…

亿发江西中小型制造企业信息化建设解决方案,2023数字化转型升级

实体经济在经济中的重要性愈发凸显&#xff0c;江西省作为制造业强省&#xff0c;要实现制造业经济高质量发展&#xff0c;信息技术与制造业的深度汇合是不可或缺的关键路径。在这个制造业转型升级的浪潮中&#xff0c;中小企业成为了江西省制造业转型的焦点。让我们深入探讨一…

Redis 7.X Linux 环境安装

Redis 简介 作为一名开发人员&#xff0c;想必大家对Redis一定是耳熟能详&#xff0c;因此在此只做简单介绍。 Remote Dictionary Server(远程字典服务)是完全开源的&#xff0c;使用ANSIC语言编写遵守BSD协议&#xff0c;是一个高性能的Key-Value内存数据库&#xff0c;它提…

分布式 - 服务器Nginx:一小时入门系列之HTTP反向代理

文章目录 1. 正向代理和反向代理2. 配置代理服务3. proxy_pass 命令解析4. 设置代理请求headers 1. 正向代理和反向代理 正向代理是客户端通过代理服务器访问互联网资源的方式。在这种情况下&#xff0c;客户端向代理服务器发送请求&#xff0c;代理服务器再向互联网上的服务器…

抖音seo矩阵系统源代码开发搭建技术分享

抖音SEO矩阵系统是一个较为复杂的系统&#xff0c;其开发和搭建需要掌握一定的技术。以下是一些技术分享&#xff1a; 技术分享 抖音SEO矩阵系统的源代码可以使用JAVA、Python、PHP等多种语言进行开发。其中&#xff0c;JAVA语言的应用较为广泛&#xff0c;因为JAVA语言有良好…

软件架构师思维塑造

一、软件系统设计的六项原则 1、单一职责原则&#xff08;Single Responsibility Principle&#xff09; 2、开闭原则&#xff08;Open Closed Principle&#xff09; 3、里氏替换原则&#xff08;Liskov Substitution Principle&#xff09; 4、迪米特法则&#xff08;Law of …

无涯教程-Lua - nested语句函数

Lua编程语言允许在另一个循环中使用一个循环。以下部分显示了一些示例来说明这一概念。 nested loops - 语法 Lua中嵌套for循环语句的语法如下- for init,max/min value, increment dofor init,max/min value, incrementdostatement(s)endstatement(s) end Lua编程语言中的…

IMV3.0

经历了两个版本&#xff0c;基础内容在前面&#xff0c;可以使用之前的基础环境&#xff1a; v1&#xff1a; https://blog.csdn.net/wtt234/article/details/132139454 v2&#xff1a; https://blog.csdn.net/wtt234/article/details/132144907 一、代码组织结构 二、代码 2.…

下载网络文件到本地

文章目录 目录 前言 操作步骤 1.引入 2.读取出文件内容 3.筛选出URL 4.下载表情包 总结 前言 这里记录一次用代码下载网络文件的过程&#xff0c;以获取抖音表情包为例。 一、操作步骤 1.引入 首先抖音有网页版&#xff0c;用浏览器就可以观看&#xff0c;用户评论发布表情在…

Webpack5 core-js和babel-loader区别和用法

文章目录 core-js是什么&#xff0c;有什么用&#xff1f;为什么使用了babel-loader对js进行兼容性配置还需要core-js?core-js的具体用法总结 core-js是什么&#xff0c;有什么用&#xff1f; core-js是一个流行的JavaScript库&#xff0c;它提供了对新的JavaScript特性、API…