给vue+element-ui动态设置主题色(包括外链样式、内联样式、行内样式)
基本思路
实现思路:实现一个mixins混入的主题js即theme.js,注册到全局下。使用el-color-picker组件切换颜色的时候,把颜色值传递到根root下,在根实例下监听主题色的变化来更改页面的主题,然后所有具体的路由页面的主题色修改通过在APP.vue页面监听路由变化来调用改变主题色方法。这里面用到providey与inject的使用,以及怎样把设置的主题色传递到根节点下,这里使用了vue1.x中的dispatch方法。
大致总结:
- 1.把得到的主题色传递给根root实例,在根实例中监听主题色的变化,并调用setThemeColor(newval, oldval)方法;
- 2.在APP.vue中监听路由变化,并调用setThemeColor(newval, oldval)方法,目的是进入具体路由页面需要修改页面的head中的style样式、DOM元素中的行内style样式;
具体实现如下。
整体效果
先看下整体实现效果:
效果预览地址:《vue+element-ui动态设置主题效果》

使用方式
设置element-ui主题色引入到main.js中
在src/styles下新建element-variables.scss:
/* 改变主题色变量 */
$--color-primary: #42b983; /* 改变 icon 字体路径变量,必需 */
$--font-path: '~element-ui/lib/theme-chalk/fonts'; @import "~element-ui/packages/theme-chalk/src/index"; :export {
colorPrimary: $--color-primary
}
在main.js中引入该css:
import variables from '@/styles/element-variables.scss'
全局混入theme.js、emitter.js
- theme.js主要方法
setThemeColor(newval, oldval),该方法传入新的颜色值与旧的颜色值; - emitter.js中使用
$$dispatch方法把修改的主题色提交到根实例下;
在main.js 中引入该两个JS并注册:
import theme from '@/mixins/theme.js'
import emitter from '@/mixins/emitter.js' Vue.mixin(theme)
Vue.mixin(emitter)
核心代码调用
- 主题色提交到根实例代码以及监听具体的路由页面修改样式(APP.vue)
export default {
name: 'App',
inject: {
themeConfig: {
default: () => ({
themeColor: '',
defaultColor: ''
})
}
},
data() {
return {
themeColor: ''
}
},
watch: {
$route() {
// 关键作用-进入到具体路由页面更新页面中DOM样式
if (typeof this.themeConfig.themeColor != 'undefined' && this.themeConfig.themeColor !== this.themeConfig.defaultColor) {
this.$nextTick(() => {
if (this.themeConfig.themeColor && this.themeConfig.defaultColor) {
this.setThemeColor(this.themeConfig.themeColor, this.themeConfig.defaultColor)
}
})
}
}
},
created() {
// 如果本地存在主题色从本地获取,并提交给root分发到页面进行渲染
if(Cookies.get('themeColor')) {
this.themeColor = Cookies.get('themeColor');
this.$$dispatch('root','root.config',[this.themeColor,true]); // 传递数组-解决初始加载执行setThemeColor两次问题
} else {
this.themeColor = this.themeConfig.themeColor;
}
},
methods: {
// 改变主题颜色
changeThemeColor(value) {
this.$$dispatch('root','root.config',value);
Cookies.set('themeColor', value, { path: '/' });
}
}
}
- 根实例监听获取的主题色并监听设置主题色(main.js)
new Vue({
el: '#app',
name: 'root',
provide(){
return {
themeConfig: this
}
},
data() {
return {
themeColor: variables.colorPrimary.toLowerCase(),
defaultColor: variables.colorPrimary.toLowerCase(),
themeFirstLoaded: true, // 主题是否第一次加载,解决初始主题watch跟$route执行setThemeColor两次问题
}
},
created() {
this.$on('root.config',(result,themeFirstLoaded) => {
this.themeColor = result.toLowerCase();
this.themeFirstLoaded = themeFirstLoaded;
})
},
watch: {
themeColor(newval, oldval) {
if(!this.themeFirstLoaded) {
this.setThemeColor(newval, oldval);
}
}
},
router,
components: { App },
template: '<App/>'
})
theme.js设置主题代码
export default {
methods: {
// 样式更新
updateStyle(stylecon, oldCulster, newCluster) {
let newStyleCon = stylecon;
oldCulster.forEach((color, index) => {
let regexp = '';
if (color.split(',').length > 1) {
const rgbArr = color.split(',');
regexp = new RegExp("\\s*" + rgbArr[0] + "\\s*,\\s*" + rgbArr[1] + "\\s*,\\s*" + rgbArr[2] + "\\s*", 'ig');
} else {
regexp = new RegExp(color, 'ig');
}
newStyleCon = newStyleCon.replace(regexp, newCluster[index])
})
return newStyleCon;
},
// 得到需要修改的一系类颜色值
getThemeCluster(theme) {
const clusters = [theme];
for (let i = 0; i <= 9; i++) {
clusters.push(this.getTintColor(theme, Number(i / 10).toFixed(2)));
}
clusters.push(this.getShadeColor(theme, 0.1));
return clusters;
},
// 得到色调颜色
getTintColor(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((255 - red) * tint);
green += Math.round((255 - green) * tint);
blue += Math.round((255 - blue) * tint);
red = red.toString(16);
green = green.toString(16);
blue = blue.toString(16);
return `#${red}${green}${blue}`
}
},
// 获取阴影色调颜色
getShadeColor(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}`
},
// 获取外链css文本内容
getCSSText(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const styleText = xhr.responseText.replace(/@font-face{[^}]+}/, '')
resolve(styleText);
}
}
xhr.open('GET', url)
xhr.send()
})
},
// 获取外链CSS样式的url地址
getRequestUrl: function(src) {
if (/^(http|https):\/\//g.test(src)) {
return src;
}
let filePath = this.getFilePath();
let count = 0;
const regexp = /\.\.\//g;
while (regexp.exec(src)) {
count++;
}
while (count--) {
filePath = filePath.substring(0, filePath.lastIndexOf('/'));
}
return filePath + "/" + src.replace(/\.\.\//g, "");
},
// 获取当前window的url地址
getFilePath: function() {
const curHref = window.location.href;
if (curHref.indexOf('/#/') != -1) {
return curHref.substring(0, curHref.indexOf('/#/'));
} else {
return curHref.substring(0, curHref.lastIndexOf('/') + 1);
}
},
// 修改主题色-head样式以及DOM行内样式
async setThemeColor(newval, oldval) {
if (typeof newval !== 'string') return;
const newThemeCluster = this.getThemeCluster(newval.replace('#', ''));
const orignalCluster = this.getThemeCluster(oldval.replace('#', ''));
// 获取原始值中包含rgb格式的值存为数组
const rgbArr = orignalCluster[1].split(',');
const orignalRGBRegExp = new RegExp("\\(\\s*" + rgbArr[0] + "\\s*,\\s*" + rgbArr[1] + "\\s*,\\s*" + rgbArr[2] +
"\\s*\\)", 'i');
// 获取外链的样式内容并替换样式
let styleTag = document.getElementById('new-configTheme__styles');
const tagsDom = document.getElementsByTagName('link');
if (!styleTag && tagsDom.length) {
styleTag = document.createElement('style')
styleTag.setAttribute('id', 'new-configTheme__styles')
document.head.appendChild(styleTag);
const tagsDomList = Array.prototype.slice.call(tagsDom);
let innerTextCon = '';
for (let i = 0; i < tagsDomList.length; i++) {
const value = tagsDomList[i];
const tagAttributeSrc = value.getAttribute('href');
const requestUrl = this.getRequestUrl(tagAttributeSrc);
const styleCon = await this.getCSSText(requestUrl);
if (new RegExp(oldval, 'i').test(styleCon) || orignalRGBRegExp.test(styleCon)) {
innerTextCon += this.updateStyle(styleCon, orignalCluster, newThemeCluster);
}
}
styleTag.innerText = innerTextCon;
}
// 获取页面的style标签
const styles = [].slice.call(document.querySelectorAll('style')).filter((style) => {
const text = style.innerText;
return new RegExp(oldval, 'i').test(text) || orignalRGBRegExp.test(text);
})
// 获取页面的style标签内容,使用updateStyle直接更新即可
styles.forEach((style) => {
const {
innerText
} = style;
if (typeof innerText !== 'string') return;
style.innerText = this.updateStyle(innerText, orignalCluster, newThemeCluster);
})
// 获取DOM元素上的style
const domAll = [].slice.call(document.getElementsByTagName('*')).filter((dom, index) => {
const stylCon = dom.getAttribute('style');
return stylCon && (new RegExp(oldval, 'i').test(stylCon) || orignalRGBRegExp.test(stylCon))
})
domAll.forEach((dom) => {
const styleCon = dom.getAttribute('style');
dom.style = this.updateStyle(styleCon, orignalCluster, newThemeCluster);
})
}
}
}
主要思路:通过传入新、旧颜色值替换head标签中样式以及DOM元素style的行内元素的样式。
重要:外链的样式最好是压缩的样式,比如在vue-cli脚手架中,本地开发环境需要把样式提取到一个文件,并且压缩,dev.config.js部分代码如下:
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 提取CSS
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') // 压缩CSS
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap,extract: true, usePostCSS: true })
},
plugins: [
// ...省略其他代码
new ExtractTextPlugin({
filename: 'bundle.css',
allChunks: true
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
})
]
})
github示例源码地址:《vue+element-ui动态主题色设置》
参考地址
给vue+element-ui动态设置主题色(包括外链样式、内联样式、行内样式)的更多相关文章
- vue + element ui 实现实现动态渲染表格
前言:之前需要做一个页面,能够通过表名动态渲染出不同的表格,这里记录一下.转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9786326.html 网站地址:我的 ...
- vue+element ui 的tab 动态增减,切换时提示用户是否切换
前言:工作中用到 vue+element ui 的前端框架,动态添加 Tab,删除 Tab,切换 Tab 时提示用户是否切换等,发现 element ui 有一个 bug,这里记录一下如何实现.转载 ...
- 基于vue(element ui) + ssm + shiro 的权限框架
zhcc 基于vue(element ui) + ssm + shiro 的权限框架 引言 心声 现在的Java世界,各种资源很丰富,不得不说,从分布式,服务化,orm,再到前端控制,权限等等玲琅满目 ...
- uni-app 动态修改主题色
老是碰到初版制作完成没多久,就整一出说什么要更改整个项目的色彩体系.真的是宝宝心里苦啊! 起初都是通过uni项目自带的uni.scss中定义,在替换页面上对应的css.以便于达到一次性修改整体布局的样 ...
- vue+element ui 的上传文件使用组件
前言:工作中用到 vue+element ui 的前端框架,使用到上传文件,则想着封装为组件,达到复用,可扩展.转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9 ...
- Vue+Element UI 实现视频上传
一.前言 项目中需要提供一个视频介绍,使用户能够快速.方便的了解如何使用产品以及注意事项. 前台使用Vue+Element UI中的el-upload组件实现视频上传及进度条展示,后台提供视频上传AP ...
- Vue+element ui table 导出到excel
需求: Vue+element UI table下的根据搜索条件导出当前所有数据 参考: https://blog.csdn.net/u010427666/article/details/792081 ...
- Vue+Element的动态表单,动态表格(后端发送配置,前端动态生成)
Vue+Element的动态表单,动态表格(后端发送配置,前端动态生成) 动态表单生成 ElementUI官网引导 Element表单生成 Element动态增减表单,在线代码 关键配置 templa ...
- 分享一个自搭的框架,使用Spring boot+Vue+Element UI
废弃,新的:https://www.cnblogs.com/hackyo/p/10453243.html 特点:前后端分离,可遵循restful 框架:后端使用Spring boot,整合了aop.a ...
- Vue + Element UI 实现权限管理系统
Vue + Element UI 实现权限管理系统 前端篇(一):搭建开发环境 https://www.cnblogs.com/xifengxiaoma/p/9533018.html
随机推荐
- 使用SVG做模型贴图的思路
大多数情况下,三维模型使用PNG,JPG作为模型的贴图,当然为了性能优化,有时候也会使用压缩贴图来提高渲染效率和较少GPU压力. 今天提供一种新的思路,使用SVG作为模型的贴图,可以达到动态调整图片精 ...
- oeasy教您玩转vim - 51 - # 读写文件
读写文件 回忆上节课内容 命令行的光标控制 方向键️️️️️可以控制左右移动 shift+️️️️️按照word左右移动光标 ctrl+b 到开头begin ctrl+e 到结尾end ctrl+w ...
- oeasy教您玩转python - 012 - # 刷新时间
刷新时间 回忆上次内容 通过搜索 我们学会 import 导入 time 了 time 是一个 module import 他可以做和时间相关的事情 time.time() 得到当前时间戳 tim ...
- C#:只支持GET和POST方法的浏览器,如何发送PUT/DELETE请求?RESTful WebAPI如何响应?
理想的RESTful WebAPI采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环境 ...
- vue小知识:多层数据双向相应之向上派发和向下派发($dispatch和$broadcast)
注意:这两个实例已经在vue3中弃用啦!!!(所以不详细说了,封装知道怎么用就行了,作为了解) 都是在vue实例配置(main.js) 向上派发:$dispatch 注意,在相应后代组件中使用 thi ...
- 推荐几款.NET开源且功能强大的实用工具,助你提高工作开发效率!
前言 俗话说得好"工欲善其事,必先利其器",今天大姚给大家推荐8款.NET开源且功能强大的实用工具,助你提高工作开发效率! DevToys 一款基于C#开源(MIT License ...
- ffmpeg一些笔记: 代码调试数据
1.AAC,MP3他的解码数据格式不支持,程序中给的是这个AV_SAMPLE_FMT_FLTP, Screen-Cpature-Recoder的codec-id为AV_CODEC_RAW_VIDEO ...
- useRoute 函数的详细介绍与使用示例
title: useRoute 函数的详细介绍与使用示例 date: 2024/7/27 updated: 2024/7/27 author: cmdragon excerpt: 摘要:本文介绍了Nu ...
- freemarker+minio实现页面静态化
什么是页面静态化? 将原本动态生成的网页内容通过某种形式转化为html并存储在服务器上,当用户请求这些页面时就不需要执行逻辑运算和数据库读 优点: 性能:提高页面加载速度和响应速度,还可以减轻数据库. ...
- 写写stream流的终结操作
终结操作和中间操作的区别:中间操作返回的一直都是stream,所以可以一直使用,但是终结操作返回的不是stream,后面不能继续操作 foreach:对流中的所有元素进行遍历操作 count:获取当前 ...