vue+element-ui實(shí)現(xiàn)主題切換功能
element-ui提供了自定義主題 自定義主題
一、安裝
- npm i element-theme -g
- npm i element-theme-chalk -D
- npm i https://github.com/ElementUI/theme-chalk -D
- 官網(wǎng)說(shuō)明安裝完成后需要et -i并會(huì)有element-variables.scss文件,但是我文件中并未找到
node_modules/.bin/et,所以手動(dòng)生成了
下圖element-variables.scss是自己寫的,因?yàn)榘惭b完成后并未生成此文件

文件中讓內(nèi)容如下`/* 改變主題色變量 */
``` /* 改變主題色變量,設(shè)置完成后會(huì)有按鈕字體等組件會(huì)變化 */ $--color-primary: #d85f6a; /* 改變 icon 字體路徑變量,必需 */ $--font-path: '~element-ui/lib/theme-chalk/fonts'; @import "~element-ui/packages/theme-chalk/src/index"; ```
頁(yè)面文件:index.vue
<el-radio-group v-model="themeRadio" @change="changeClick" size="mini">
<el-radio label="#d85f6a">紅色主題</el-radio>
<el-radio label="#409EFF">藍(lán)色主題</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文件,文件內(nèi)容如下:
<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:{ //在頁(yè)面中將colorVal傳進(jìn)來(lái)
colorVal:{
type:String,
}
},
created(){
// let option={
// background:'#FFFFFF'
// }
this.loadingInstance =Loading.service(); //這里增加加載loadding,因?yàn)樗⑿马?yè)面會(huì)出現(xiàn)延遲
},
data() {
return {
chalk: '', // content of theme-chalk css
theme: '',
loadingInstance:true
}
},
computed: {
defaultTheme() {
// 將選擇的顏色屬性保存在vuex中,如果頁(yè)面刷新娶不到就從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(() => { // 以服務(wù)的方式調(diào)用的 Loading 需要異步關(guān)閉
// 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進(jìn)制顏色標(biāo)號(hào)進(jìn)行處理,
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>效果:


但是到現(xiàn)在有個(gè)問(wèn)題,就是element-ui有自己的ui主題,每次radio切換主題時(shí)沒(méi)問(wèn)題,但是F5刷新后頁(yè)面元素顏色會(huì)閃爍,順序:element-ui顏色>當(dāng)前設(shè)置緩存顏色,為了解決這個(gè)問(wèn)題,就優(yōu)化了代碼,在APP.vue中設(shè)置,當(dāng)頁(yè)面刷新時(shí)能更快的渲染
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中此方法拿出來(lái)
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()
},
到此這篇關(guān)于vue+element-ui實(shí)現(xiàn)主題切換的文章就介紹到這了,更多相關(guān)vue主題切換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue組件props不同數(shù)據(jù)類型傳參的默認(rèn)值問(wèn)題
這篇文章主要介紹了vue組件props不同數(shù)據(jù)類型傳參的默認(rèn)值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
vue?路由切換過(guò)渡動(dòng)效滑入滑出效果的實(shí)例代碼
在支付寶賬單頁(yè)面有這樣一個(gè)特效切換過(guò)渡動(dòng)效滑入滑出效果,非常方便實(shí)用,那么這個(gè)功能如何實(shí)現(xiàn)的呢?下面小編通過(guò)vue實(shí)現(xiàn)路由切換過(guò)渡動(dòng)效滑入滑出效果,感興趣的朋友一起看看吧2022-03-03
vue中使用gantt-elastic實(shí)現(xiàn)可拖拽甘特圖的示例代碼
這篇文章主要介紹了vue中使用gantt-elastic實(shí)現(xiàn)可拖拽甘特圖,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
vue使用keep-alive無(wú)效以及include和exclude用法解讀
這篇文章主要介紹了vue使用keep-alive無(wú)效以及include和exclude用法解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
echarts.js 動(dòng)態(tài)生成多個(gè)圖表 使用vue封裝組件操作
這篇文章主要介紹了echarts.js 動(dòng)態(tài)生成多個(gè)圖表 使用vue封裝組件操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
vue 動(dòng)態(tài)設(shè)置img的src地址無(wú)效,npm run build 后找不到文件的解決
這篇文章主要介紹了vue 動(dòng)態(tài)設(shè)置img的src地址無(wú)效,npm run build 后找不到文件的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
element?ui富文本編輯器的使用效果與步驟(quill-editor)
富文本編輯器在任何項(xiàng)目中都會(huì)用到,在Element中我們推薦vue-quill-editor組件,下面這篇文章主要給大家介紹了關(guān)于element?ui富文本編輯器的使用效果與步驟(quill-editor)的相關(guān)資料,需要的朋友可以參考下2022-10-10
Vue 清除Form表單校驗(yàn)信息的解決方法(清除表單驗(yàn)證上次提示信息)
這篇文章主要介紹了Vue 清除Form表單校驗(yàn)信息的解決方法(清除表單驗(yàn)證上次提示信息),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04

