Vue+ElementUI實(shí)現(xiàn)動(dòng)態(tài)更換任意主題色(動(dòng)態(tài)換膚)的全過(guò)程
前言
最近基于 ElementUI 的項(xiàng)目上需要實(shí)現(xiàn)動(dòng)態(tài)換膚的功能,這里提供兩種方式:
vue-element-admin官方實(shí)現(xiàn)的方式webpack-theme-color-replacer插件的實(shí)現(xiàn)方式
vue-element-admin 官方實(shí)現(xiàn)的方式
簡(jiǎn)單說(shuō)明一下它的原理: element-ui 2.0 版本之后所有的樣式都是基于 SCSS 編寫(xiě)的,所有的顏色都是基于幾個(gè)基礎(chǔ)顏色變量來(lái)設(shè)置的,所以就不難實(shí)現(xiàn)動(dòng)態(tài)換膚了,只要找到那幾個(gè)顏色變量修改它就可以了。 首先我們需要拿到通過(guò) package.json 拿到 element-ui 的版本號(hào),根據(jù)該版本號(hào)去請(qǐng)求相應(yīng)的樣式。拿到樣式之后將樣色,通過(guò)正則匹配和替換,將顏色變量替換成你需要的,之后動(dòng)態(tài)添加 style 標(biāo)簽來(lái)覆蓋原有的 css 樣式。
1、這里無(wú)腦參考 vue-element-admin 的源碼,首先現(xiàn)在 styles 文件夾下創(chuàng)建一個(gè)名為 element-variables.scss 文件,并在 main.js 中引入該文件。
/* src/styles/element-variables.scss */
/* 改變主題色變量 */
$--color-primary: #256DCB;
$--color-success: #7AC800;
$--color-danger: #EC4242;
$--color-info: #999999;
/* 改變 icon 字體路徑變量,必需 */
$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import "~element-ui/packages/theme-chalk/src/index";
/* 如遇到導(dǎo)出的變量值為 undefined 則本文件名需要改成 element-variables.module.scss */
:export {
theme: $--color-primary
}
/* main.js */ import Vue from 'vue' import Element from 'element-ui' import './element-variables.scss' Vue.use(Element)
2、通過(guò)以上方式已經(jīng)能夠?qū)崿F(xiàn) ElementUI 主題替換了,但是想要做到自定義顏色還是遠(yuǎn)遠(yuǎn)不夠的,考慮到主題色在整個(gè)項(xiàng)目中都有應(yīng)用,所以我們將它存到 Vuex 中,接下來(lái)要做的就是在 store/modules 下新建 settings.js 。
/* src/store/modules/settings.js */
import variables from '@/styles/element-variables.module.scss'
import * as Types from '../mutation-types'
const state = {
theme: variables.theme
}
const mutations = {
CHANGE_SETTING: (state, { key, value }) => {
localStorage.setItem('theme', value) // 緩存起來(lái),刷新的時(shí)候重新取用
// eslint-disable-next-line no-prototype-builtins
if (state.hasOwnProperty(key)) {
state[key] = value
}
}
}
const actions = {
changeSetting ({ commit }, data) {
commit('CHANGE_SETTING', data)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
3、這一步也是無(wú)腦 copy vue-element-admin 的源碼,新建一個(gè)名為 ThemePicker 的組件,代碼如下:
/* src/components/ThemePicker/index.vue */
<template>
<el-color-picker
v-model="theme"
:predefine="['#256DCB', '#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', '#F80', ]"
class="theme-picker"
popper-class="theme-picker-dropdown"
/>
</template>
<script>
import { chalkCss } from './chalk.js' // 就是 getCSSString 接口中獲取的 css,這里我將版本號(hào)固定并且把 css 緩存到本地,記得處理 \ 轉(zhuǎn)義問(wèn)題
// const version = require('element-ui/package.json').version // element-ui version from node_modules
const ORIGINAL_THEME = '#409EFF' // default color chalk.js 中的 primary color,根據(jù)此顏色計(jì)算出一系列顏色進(jìn)行正則替換
export default {
name: 'ThemePicker',
data () {
return {
chalk: '', // content of theme-chalk css
theme: ''
}
},
computed: {
defaultTheme () {
return this.$store.state.settings.theme
}
},
watch: {
defaultTheme: {
handler: function (val, oldVal) {
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('#', ''))
console.log(themeCluster, originalCluster)
const $message = this.$message({
message: this.$t('theme_compiling'),
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')
this.chalk = chalkCss.replace(/@font-face{[^}]+}/, '') // 本地緩存,如果需要獲取線上的就用上面那種方式,優(yōu)點(diǎn):切換無(wú)延遲,缺點(diǎn):需要手動(dòng)維護(hù) css string
}
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()
}
},
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()
})
},
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>
4、最后在頁(yè)面中使用 ThemePicker 組件,我這里是放到 header 里。
// template
<theme-picker @change="themeChange" />
// js
import ThemePicker from '@/components/ThemePicker'
// methods
themeChange (val) {
this.$store.dispatch('settings/changeSetting', {
key: 'theme',
value: val
})
}
到這里為止就已經(jīng)實(shí)現(xiàn)了全部動(dòng)態(tài)換膚的功能,不過(guò)還有一個(gè)問(wèn)題就是刷新頁(yè)面之后,主題色會(huì)重置,所以在切換的時(shí)候需要將主題色緩存到 localStore 中去,為了在任意頁(yè)面刷新都可以加載主題色,我選擇在 App.vue 頁(yè)面也增加一個(gè) ThemePicker 組件,具體實(shí)現(xiàn)見(jiàn)如下代碼:
/* src/App.vue */
<template>
<div id="app" :style="{'--color': defaultTheme}">
<theme-picker @change="themeChange" v-show="false" />
<router-view />
</div>
</template>
<script>
import ThemePicker from '@/components/ThemePicker'
export default {
name: 'App',
components: { ThemePicker },
computed: {
defaultTheme () {
return this.$store.state.settings.theme
}
},
mounted () {
if (localStorage.getItem('theme')) {
this.themeChange(localStorage.getItem('theme'))
}
},
methods: {
themeChange (val) {
this.$store.dispatch('settings/changeSetting', {
key: 'theme',
value: val
})
}
}
}
</script>
另外一些自己定義的樣式如果需要用到主題色可以用 css 變量,但需要預(yù)先在 root 上定義好變量,我這里使用 vue 雙向綁定將主題色綁定到 :style="{'--color': defaultTheme}" (具體用法見(jiàn)上面代碼),這樣就能在任何組件下使用該主題色了(注意:該方法 IE 瀏覽器不支持),代碼如下:
<div class="box"></div>
.box {
width: 100px;
height: 100px;
background-color: var(--color);
}
提示:
- 如果 scss 文件導(dǎo)出的是空對(duì)象,則需要將 scss 文件名稱改成 xxx.module.scss 的形式,CSS Modules。
- 如果需要緩存 chalkCss 的,css string 中的 \ 會(huì)被轉(zhuǎn)義,記得手動(dòng)改成 \\,不然 ElementUI 自帶的 icon 展示不出來(lái)。
參考文檔:
webpack-theme-color-replacer 插件的實(shí)現(xiàn)方式
此方式親測(cè)可用,本質(zhì)上也是顏色的替換,但是跟 ElementUI 稍稍有點(diǎn)兼容性問(wèn)題,具體實(shí)現(xiàn)方式見(jiàn) webpack-theme-color-replacer 的使用,我這里就不做過(guò)多贅述了。
總結(jié)
到此這篇關(guān)于Vue+ElementUI實(shí)現(xiàn)動(dòng)態(tài)更換任意主題色(動(dòng)態(tài)換膚)的文章就介紹到這了,更多相關(guān)Vue ElementUI動(dòng)態(tài)更換任意主題色內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue.js獲取被選擇的option的value和text值方法
今天小編就為大家分享一篇Vue.js獲取被選擇的option的value和text值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
vue雙向數(shù)據(jù)綁定指令v-model的用法
這篇文章主要介紹了vue雙向數(shù)據(jù)綁定指令v-model的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
vue3中配置文件vue.config.js不生效的解決辦法
這篇文章主要介紹了vue3中配置文件vue.config.js不生效的解決辦法,文中通過(guò)代碼示例講解的非常詳細(xì),對(duì)大家解決問(wèn)題有一定的幫助,需要的朋友可以參考下2024-05-05
windows下vue-cli及webpack搭建安裝環(huán)境
這篇文章主要介紹了windows下vue-cli及webpack搭建安裝環(huán)境,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04
vue3模塊創(chuàng)建runtime-dom源碼解析
這篇文章主要為大家介紹了vue3模塊創(chuàng)建runtime-dom源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
解決vue-router 切換tab標(biāo)簽關(guān)閉時(shí)緩存問(wèn)題
這篇文章主要介紹了解決vue-router 切換tab標(biāo)簽關(guān)閉時(shí)緩存問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
Vue TypeScript使用eval函數(shù)遇到的問(wèn)題
近幾年前端對(duì) TypeScript的呼聲越來(lái)越高,Typescript也成為了前端必備的技能。TypeScript是JS類型的超集,并支持了泛型、類型、命名空間、枚舉等特性,彌補(bǔ)了 JS 在大型應(yīng)用開(kāi)發(fā)中的不足2023-01-01
如何巧用Vue.extend繼承組件實(shí)現(xiàn)el-table雙擊可編輯(不使用v-if、v-else)
這篇文章主要給大家介紹了關(guān)于如何巧用Vue.extend繼承組件實(shí)現(xiàn)el-table雙擊可編輯的相關(guān)資料,不使用v-if、v-else,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06

