vue+element-ui实现主题切换
vue+element-ui设置主题变换
·
element-ui提供了自定义主题 自定义主题
一、安装
-
npm i element-theme -g
-
npm i element-theme-chalk -D
-
npm i https://github.com/ElementUI/theme-chalk -D
-
官网说明安装完成后需要et -i并会有element-variables.scss文件,但是我文件中并未找到
node_modules/.bin/et
,所以手动生成了 -
下图element-variables.scss是自己写的,因为安装完成后并未生成此文件
-
文件中让内容如下`/* 改变主题色变量 */
``` /* 改变主题色变量,设置完成后会有按钮字体等组件会变化 */ $--color-primary: #d85f6a; /* 改变 icon 字体路径变量,必需 */ $--font-path: '~element-ui/lib/theme-chalk/fonts'; @import "~element-ui/packages/theme-chalk/src/index"; ```
页面文件:index.vue
<el-radio-group v-model="themeRadio" @change="changeClick" size="mini">
<el-radio label="#d85f6a">红色主题</el-radio>
<el-radio label="#409EFF">蓝色主题</el-radio>
</el-radio-group>
文件引入:
import ColorPicker from "@/layout/colorpicker/index";
使用:
<color-picker :colorVal="colorVal"></color-picker>
方法:
changeClick(value){
this.colorVal = value
localStorage.setItem('skin',value)
this.$store.commit("setSkin",value)
},
- colorpicker.vue文件,文件内容如下:
<template>
<el-color-picker
v-if="false"
v-model="theme"
:predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
class="theme-picker"
popper-class="theme-picker-dropdown"
/>
</template>
<script>
const version = require('element-ui/package.json').version // element-ui version from node_modules
const ORIGINAL_THEME = '#409EFF' // default color
import { Loading } from 'element-ui';
export default {
props:{ //在页面中将colorVal传进来
colorVal:{
type:String,
}
},
created(){
// let option={
// background:'#FFFFFF'
// }
this.loadingInstance =Loading.service(); //这里增加加载loadding,因为刷新页面会出现延迟
},
data() {
return {
chalk: '', // content of theme-chalk css
theme: '',
loadingInstance:true
}
},
computed: {
defaultTheme() {
// 将选择的颜色属性保存在vuex中,如果页面刷新娶不到就从ocalStorage中取
if(this.$store.state.skin) return this.$store.state.skin;
else return localStorage.getItem('skin')
// return this.$store.state.skin
}
},
watch: {
defaultTheme:{
handler: function(val) {
this.$nextTick(() => {
// this.$emit('input', this.model);
this.theme = val
})
},
immediate: true
},
async theme(val) {
const oldVal = this.chalk ? this.theme : ORIGINAL_THEME
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
const $message = this.$message({
message: ' Compiling the theme',
customClass: 'theme-message',
type: 'success',
duration: 0,
iconClass: 'el-icon-loading'
})
const getHandler = (variable, id) => {
return () => {
const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))
const newStyle = this.updateStyle(this[variable], 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', 'chalk-style')
chalkHandler()
const styles = [].slice.call(document.querySelectorAll('style'))
.filter(style => {
const text = style.innerText
return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
})
styles.forEach(style => {
const { innerText } = style
if (typeof innerText !== 'string') return
style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)
})
this.$emit('change', val)
$message.close()
// this.$message({
// message:'皮肤切换成功',
// type:'success'
// })
this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
// this.loadingInstance.close();
})
setTimeout(()=>{
this.loadingInstance.close();
},1000)
}
},
methods: {
updateStyle(style, oldCluster, newCluster) {
let newStyle = style
oldCluster.forEach((color, index) => {
newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
})
return newStyle
},
getCSSString(url, variable) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')
resolve()
}
}
xhr.open('GET', url)
xhr.send()
})
},
//将传入的24进制颜色标号进行处理,
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 space
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>
<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>
效果:
但是到现在有个问题,就是element-ui有自己的ui主题,每次radio切换主题时没问题,但是F5刷新后页面元素颜色会闪烁,顺序:element-ui颜色>当前设置缓存颜色,为了解决这个问题,就优化了代码,在APP.vue中设置,当页面刷新时能更快的渲染
1.新建colorpicker.js文件
2.APP.vue中引入
//colorpicker.js中只保留了 colorpicker.vue 中 methods:中的方法
import colorpicker from '@/mixins/colorpicker.js'
3.使用mixins模式
mixins:[colorpicker],
在created中使用
async created() {
await this.getColor('#409EFF')
await this.configRouter();
},
//将colorpicker.vue中此方法拿出来
async getColor(val){
let theme = val
const oldVal = this.chalk ? theme : ORIGINAL_THEME
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
const $message = this.$message({
message: ' Compiling the theme',
customClass: 'theme-message',
type: 'success',
duration: 0,
iconClass: 'el-icon-loading'
})
const getHandler = (variable, id) => {
return () => {
const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))
const newStyle = this.updateStyle(this[variable], 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', 'chalk-style')
chalkHandler()
const styles = [].slice.call(document.querySelectorAll('style'))
.filter(style => {
const text = style.innerText
return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
})
styles.forEach(style => {
const { innerText } = style
if (typeof innerText !== 'string') return
style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)
})
this.$emit('change', val)
$message.close()
},
更多推荐
已为社区贡献5条内容
所有评论(0)