ElementUI主题颜色动态切换并缓存

今天给大家分享一下在Vue中使用ElementUI时,想切换主题颜色的两种方式。

第一种:静态改变项目中的主题颜色

比较简单,稍微带过:

项目中创建element-variables.scss文件,编写内容:

css 复制代码
/* 改变主题色变量 */
$--color-primary: teal;

/* 改变 icon 字体路径变量,必需 */
$--font-path: '~element-ui/lib/theme-chalk/fonts';

@import "~element-ui/packages/theme-chalk/src/index";

之后,在项目的入口文件中,直接引入以上样式文件即可(无需引入 Element 编译好的 CSS 文件)

javascript 复制代码
import Vue from 'vue'
import Element from 'element-ui'
import './element-variables.scss'

Vue.use(Element)

第二种:重点!!!动态切换主题颜色并做缓存

  1. 创建theme.js文件,作为工具类,并写入以下内容:
javascript 复制代码
const __DEFUALT__COLOR = "#409EFF"
const version = require('element-ui/package.json').version

class Theme {
  constructor() {
    const color = this._getLocalTheme() || __DEFUALT__COLOR;
    const oldVal = this._getLocalTheme() || __DEFUALT__COLOR;
    this.changeTheme(color, oldVal);
    this.chalk = ''
  }
  async changeTheme($color, oldVal) {
    const themeCluster = this._getThemeCluster($color.replace('#', ''))
    const originalCluster = this._getThemeCluster(oldVal.replace('#', ''))
    const getHandler = (id) => {
      return () => {
        const originalCluster = this._getThemeCluster(__DEFUALT__COLOR.replace('#', ''))
        const newStyle = this._updateStyle(this.chalk, 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-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._setLocalTheme("--primary-color", $color)
  }
  _getLocalTheme(key = "--primary-color") {
    return key && localStorage.getItem(key);
  }
  _setLocalTheme(key, value) {
    localStorage[key] = value;
  }
  _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
  }
  _updateStyle(style, oldCluster, newCluster) {
    let newStyle = style
    oldCluster.forEach((color, index) => {
      newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
    })
    return newStyle
  }
  _getCSSString(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          this.chalk = xhr.responseText.replace(/@font-face{[^}]+}/, '')
          resolve()
        }
      }
      xhr.open('GET', url)
      xhr.send()
    })
  }
}

export default Theme
  1. 然后在项目入口main.js中引入即可
javascript 复制代码
import Vue from 'vue'
import Theme from "./utils/theme
Vue.prototype.$theme = new Theme()
  1. 在ThemePicker中使用
javascript 复制代码
<template>
  <el-color-picker
    v-model="theme"
    :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
    class="theme-picker"
    popper-class="theme-picker-dropdown"
  />
</template>

<script>

export default {
  data() {
    return {
      theme: ''
    }
  },
  computed: {
    defaultTheme() {
      return this.$store.state.settings.theme
    }
  },
  watch: {
    defaultTheme: {
      handler: function(val, oldVal) {
        this.theme = val
      },
      immediate: true
    },
    theme(val, oldVal) {
      this.$theme.changeTheme(val, oldVal)
      this.$store.dispatch('settings/changeSetting', {
        key: 'theme',
        value: val
      })
    }
  }
}
</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>
相关推荐
IT_陈寒9 分钟前
Java性能优化:从这8个关键指标开始,让你的应用提速50%
前端·人工智能·后端
天生我材必有用_吴用11 分钟前
Vue3+Node.js 实现大文件上传:断点续传、秒传、分片上传完整教程(含源码)
前端
摸鱼的春哥27 分钟前
前端程序员最讨厌的10件事
前端·javascript·后端
酷ku的森1 小时前
Redis中的Zset数据类型
数据库·redis·缓存
牧羊狼的狼4 小时前
React 中的 HOC 和 Hooks
前端·javascript·react.js·hooks·高阶组件·hoc
知识分享小能手6 小时前
React学习教程,从入门到精通, React 属性(Props)语法知识点与案例详解(14)
前端·javascript·vue.js·学习·react.js·vue·react
魔云连洲6 小时前
深入解析:Vue与React的异步批处理更新机制
前端·vue.js·react.js
mCell6 小时前
JavaScript 的多线程能力:Worker
前端·javascript·浏览器
超级无敌攻城狮8 小时前
3 分钟学会!波浪文字动画超详细教程,从 0 到 1 实现「思考中 / 加载中」高级效果
前端
excel9 小时前
用 TensorFlow.js Node 实现猫图像识别(教学版逐步分解)
前端