element ui动态更换主题色

vue yekong

vue项目开发要求页面实现换肤功能,除了部分地区自行事先定义好以外,使用的element ui也要随着更换主题色。
element ui动态更换主题色

封装组件

组件改自ThemePicker

<template>
  <div>

  </div>
</template>

<script>
const version = require('element-ui/package.json').version // element-ui version from node_modules
const ORIGINAL_THEME = '#409EFF' // default color
export default {
  data() {
    return {
      chalk: '', // content of theme-chalk css
      // theme: ''
    }
  },
  computed: {
    defaultTheme() {
      return this.$store.state.settings.theme
    }
  },
  props: {
    theme: {
      type: String,
      default() {
        return ''
      }
    }
  },
  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 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)
    }
  },
  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 lang="scss" scoped>

</style>

使用

App.vue

<template>
  <div id="app">
    <router-view/>
    <changeTheme v-if="theme" :theme="theme"></changeTheme>
  </div>
</template>

<script>
import changeTheme from '@/components/changeTheme'

export default {
  name: 'app',
  mounted() {
    this.changeSkin()
  },
  computed: {
    theme() {
      var name = '#232959'
      this.list.forEach((type) => {
        if (this.themeName == type.name) {
          name = type.theme
        }
      })
      return name
    }
  },
  data() {
    return {
      themeName: '',
      list: [{
        name: 'deepBlue',
        theme: '#232959'
      }, {
        name: 'Blue',
        theme: '#0657BB'
      }, {
        name: 'purple',
        theme: '#7128CB'
      }, {
        name: 'green',
        theme: '#15A073'
      }]
    }
  },
  components: { changeTheme },
  methods: {
    // 换肤
    changeSkin() {
      var that = this
      let theme = localStorage.getItem('theme')
      if (!theme) {
        window.document.documentElement.setAttribute('data-theme', 'deepBlue')
      } else {
        this.themeName = theme
        window.document.documentElement.setAttribute('data-theme', theme)
      }
    }
  }
}
</script>

换肤组件

/**
* @Author: 858834013@qq.com
* @Name: changeSkin
* @Date: 2022-02-07
* @Desc:
*/
<template>
  <div class="Home">
    <pageTop title="更换主题"></pageTop>
    <div class="pageMain">
      <div class="listInfo">
        <div v-for="(item,index) in themeList" :key="index" @click="changeSkin(item)">
          <item :themeId="themeId" :item="item">
            {{ item }}
          </item>
        </div>
      </div>
    </div>
    <changeTheme v-if="theme" :theme="theme"></changeTheme>
  </div>
</template>

<script>
import item from '@/views/changeSkin/item'
import pageTop from '@/components/pageTop'
import changeTheme from '@/components/changeTheme'

export default {
  name: 'Home',
  data() {
    return {
      // 选中的主题
      themeId: '',
      // 主题数据
      themeList: ['deepBlue', 'Blue', 'purple', 'green'],
      themeName: '',
      list: [{
        name: 'deepBlue',
        theme: '#232959'
      }, {
        name: 'Blue',
        theme: '#0657BB'
      }, {
        name: 'purple',
        theme: '#7128CB'
      }, {
        name: 'green',
        theme: '#15A073'
      }]
    }
  },
  components: { item, pageTop,changeTheme },
  mounted() {
    if (localStorage.getItem('theme')) {
      this.themeId = localStorage.getItem('theme')
    } else {
      this.themeId = 'deepBlue'
    }
  },
  computed: {
    theme() {
      var name = '#232959'
      this.list.forEach((type) => {
        if (this.themeName == type.name) {
          name = type.theme
        }
      })
      return name
    }
  },
  methods: {
    // 换肤
    changeSkin(mode) {
      this.themeId = mode
      this.themeName = mode
      if (!mode) {
        window.document.documentElement.setAttribute('data-theme', 'blue')
        localStorage.setItem('theme', 'blue')
      } else {
        window.document.documentElement.setAttribute('data-theme', mode)
        localStorage.setItem('theme', mode)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.Home {
  width: 100%;
  height: calc(100% - 0px);
  position: relative;

  .listInfo {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    flex-wrap: wrap;
    flex-direction: row;
  }
}


</style>


可结合vue项目实现换肤功能使用。

喜欢