一、固定多套主题换肤

原理:本方法是最常见的换肤方式,本地存放多套主题,两者有不同的命名空间,如写两套主题,一套叫 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>
	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)
    }
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 }
main.js
 // CSS入口文件
import '@/styles/index.scss'
// 主题初始化
import { initThemes } from './utils/themes'
initThemes()
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、通过package.json拿到element-ui的版本号
const version = require('element-ui/package.json').version
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()
}
3、通过正则匹配和替换颜色
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },
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()
优点:无需准备多套主题,可以自由动态换肤
缺点:自定义不够,只支持基础颜色的切换
附:详细代码
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
    }
   }
}
Logo

前往低代码交流专区

更多推荐