element-ui 動態換膚

一、在安裝好 element-ui@2.x 之後,首先安裝sass-loadercss

npm i sass-loader node-sass -D

二、安裝 element-themevue

npm i element-theme -D

三、安裝 theme-chalknode

npm i element-theme-chalk -D
# or from github
npm i https://github.com/ElementUI/theme-chalk -D

四、初始化變量文件git

et -i // 默認的文件是element-variables.scss,也能夠自定義文件名 et --init [file path]

安裝成功之後,在項目裏會自動生成一個 element-variables.scss 文件,以下圖:github

裏面定義的是全部的顏色變量npm

固然,這一步也有可能失敗,命令行提示找不到et 這個命令。這個時候須要按照步驟一,從新裝一下sass-loaderelement-ui

五、修改變量json

直接編輯 element-variables.scss 文件,例如修改主題色爲紅色sass

六、編譯主題app

保存文件後,到命令行裏執行 et 編譯主題,若是你想啓用 watch 模式,實時編譯主題,增長 -w 參數;若是你在初始化時指定了自定義變量文件,則須要增長 -c 參數,並帶上你的變量文件名

此時,項目中會自動生成一個theme文件夾,裏面是編譯後全部的字體文件和樣式文件

七、引入自定義主題

默認狀況下編譯的主題目錄是放在 ./theme 下,你能夠經過 -o 參數指定打包目錄。像引入默認主題同樣,在代碼裏直接引用 theme/index.css 文件便可。

import '../theme/index.css'
import ElementUI from 'element-ui'
import Vue from 'vue'

Vue.use(ElementUI)

啓動項目,會發現原來默認的藍色會變成紅色

 

官網提供的這種方法僅適用於一次性的更改全局主題顏色,若是想實現官網2.0版本右上角,使用 ColorPicker 顏色選擇器 動態換膚。那麼建議參考 vue-element-admin,做者的 《手摸手,帶你用vue擼後臺》 系列文章很是精彩

ThemePicker.vue

<template>
  <el-tooltip effect="dark" content="theme" placement="bottom">
    <el-color-picker
    v-model="theme"
    class="theme-picker"
    size="small"
    popper-class="theme-picker-dropdown"/>
  </el-tooltip>
</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: ORIGINAL_THEME
    }
  },
  watch: {
    theme(val, oldVal) {
      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
        }
      }

      const chalkHandler = getHandler('chalk', 'chalk-style')

      if (!this.chalk) {
        const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
        this.getCSSString(url, chalkHandler, 'chalk')
      } else {
        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.$message({
        message: '換膚成功',
        type: 'success'
      })
    }
  },

  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, 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()
    },

    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>
Navbar.vue

<template>
  <el-menu class="navbar" mode="horizontal">
    <hamburger 
      class="hamburger-container"
      :toggleClick="toggleSideBar"
      :isActive="!sidebar.opened">
    </hamburger>
    <div class="right-menu">
      <screenfull class="screenfull"></screenfull>
      <div class="lang">
        <el-dropdown>
          <i class="iconfont icon-language4"></i>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="toggleLang('zh')" :disabled="$i18n.locale == 'zh'">中文</el-dropdown-item>
            <el-dropdown-item @click.native="toggleLang('en')" :disabled="$i18n.locale == 'en'">English</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <theme-picker></theme-picker>
    </div>
  </el-menu>
</template>

 

以上demo代碼地址:https://github.com/frwupeng517/element-admin

Element-UI 官方文檔地址:http://element-cn.eleme.io/#/zh-CN/component/custom-theme

PanJiachen Git地址:https://github.com/PanJiaChen/vue-element-admin

相關文章
相關標籤/搜索