当前位置:   article > 正文

VUE+ElementUI项目换肤功能_element换肤原理

element换肤原理

一、固定多套主题换肤

原理:本方法是最常见的换肤方式,本地存放多套主题,两者有不同的命名空间,如写两套主题,一套叫 light-themes ,一套叫 dark-themes,dark-themes 主题都在一个 .dark-themes 的命名空间下,我们动态的在 body 上 add .dark-themes ; remove .light-theme。

设置页面 (views/layout.vue)
	<el-radio-group v-model="options.themes" @change="applySetting" size="mini">
        <el-radio-button label="light-themes">Light</el-radio-button>
        <el-radio-button label="dark-themes">Dark</el-radio-button>
     </el-radio-group>
  • 1
  • 2
  • 3
  • 4
	import { setThemes } from '@/utils/themes'
	applySetting() {
      setThemes(this.options.themes)
      this.defaultThemes = this.options.themes
      window.localStorage.setItem('themes', this.options.themes)
      this.defaultConfig = JSON.stringify(this.options)
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
themes.js (@/utils/themes)
function setThemes(themes) {
  themes = ['dark-themes', 'light-themes'].includes(themes) ? themes : 'dark-themes'
  document.querySelector('html').setAttribute('class', themes)
}

function initThemes() {
  const themes = localStorage.getItem('themes') || 'dark-themes'
  setThemes(themes)
}
export { initThemes, setThemes }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
main.js
 // CSS入口文件
import '@/styles/index.scss'
// 主题初始化
import { initThemes } from './utils/themes'
initThemes()
  • 1
  • 2
  • 3
  • 4
  • 5
css相关结构及内容

在这里插入图片描述

index.css (css 入口文件)

在这里插入图片描述

dark.css (主题文件)

在这里插入图片描述

二、Element-UI动态换肤

原理:element-ui 2.0版本之后所有的样式都是基于SCSS编写的,所有的颜色都是基于几个基础颜色变量来设置的,所以就不难实现动态换肤了,只要找到首先我们需要拿到通过package.json拿到element-ui的版本号,根据该版本号去请求相应的样式。拿到样式之后将样色,通过正则匹配和替换,将颜色变量替换成你需要的,之后动态添加style标签来覆盖重叠的css样式。

注:获取element-ui的版本号的目的是为了锁定版本,避免将来Element升级时受到非兼容性更新的影响。

颜色选择器

<el-color-picker
        v-model="theme"
        :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
      />
  • 1
  • 2
  • 3
  • 4
1、通过package.json拿到element-ui的版本号
const version = require('element-ui/package.json').version
  • 1
2、根据该版本号去请求相应的样式
const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
this.getCSSString(url, chalkHandler, 'chalk')

getCSSString(url, callback, variable) {
  const xhr = new XMLHttpRequest()
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')
      callback()
    }
  }
  xhr.open('GET', url)
  xhr.send()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
3、通过正则匹配和替换颜色
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
4、动态添加style标签来覆盖重叠的css样式
	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
        }
      }
      const chalkHandler = getHandler('chalk', 'chalk-style')
      chalkHandler()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
优点:无需准备多套主题,可以自由动态换肤
缺点:自定义不够,只支持基础颜色的切换
附:详细代码
const version = require('element-ui/package.json').version // 从node_modules中获取element-ui 版本号
const ORIGINAL_THEME = '#409EFF' // 默认主题色

export default {
  data() {
    return {
      chalk: '', // content of theme-chalk css
      theme: ''
    }
  },
  
  mounted() {
    if(localStorage.getItem('colorPicker')){
      this.theme = localStorage.getItem('colorPicker')
    }
  },
  
  watch: {
   //  监听主题变更并编译主题
    async theme(val) {
      const oldVal = this.chalk ? this.theme : ORIGINAL_THEME

      if (typeof val !== 'string') return
      
      localStorage.setItem('colorPicker',val)
      //  获取新老主题色的色值集合
      const themeCluster = this.getThemeCluster(val.replace('#', ''))
      const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
      
      const $message = this.$message({
        message: '正在编译主题',
        type: 'success',
        duration: 0,
        iconClass: 'el-icon-loading'
      })
      // 将style渲染到DOM中
      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
        }
      }
      //  初次进入或刷新时动态加载CSS文件
      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)
      })
      
      $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++) {
        console.log(Number((i / 10).toFixed(2)))
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    }
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/82044
推荐阅读