• vue+ element 动态换肤


    转至 https://www.cnblogs.com/dengqichang/p/10364455.html

    一、搭建好项目的环境。
    
    二、根据ElementUI官网的自定义主题(http://element.eleme.io/#/zh-CN/component/custom-theme)来安装【主题生成工具】。
    
    首先安装「主题生成工具」,可以全局安装或者安装在当前项目下,推荐安装在项目里,方便别人 clone 项目时能直接安装依赖并启动,这里以全局安装做演示。
    
    npm i element-theme -g
    安装白垩主题,可以从 npm 安装或者从 GitHub 拉取最新代码。
    
    # 从 npm
    npm i element-theme-chalk -D
    
    # 从 GitHub
    npm i https://github.com/ElementUI/theme-chalk -D
    ¶初始化变量文件
    主题生成工具安装成功后,如果全局安装可以在命令行里通过 et 调用工具,如果安装在当前目录下,需要通过 node_modules/.bin/et 访问到命令。执行 -i 初始化变量文件。默认输出到 element-variables.scss,当然你可以传参数指定文件输出目录。
    
    et -i [可以自定义变量文件]
    
    > ✔ Generator variables file
    如果使用默认配置,执行后当前目录会有一个 element-variables.scss 文件。内部包含了主题所用到的所有变量,它们使用 SCSS 的格式定义。大致结构如下:
    
    $--color-primary: #409EFF !default;
    $--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */
    $--color-primary-light-2: mix($--color-white, $--color-primary, 20%) !default; /* 66b1ff */
    $--color-primary-light-3: mix($--color-white, $--color-primary, 30%) !default; /* 79bbff */
    $--color-primary-light-4: mix($--color-white, $--color-primary, 40%) !default; /* 8cc5ff */
    $--color-primary-light-5: mix($--color-white, $--color-primary, 50%) !default; /* a0cfff */
    $--color-primary-light-6: mix($--color-white, $--color-primary, 60%) !default; /* b3d8ff */
    $--color-primary-light-7: mix($--color-white, $--color-primary, 70%) !default; /* c6e2ff */
    $--color-primary-light-8: mix($--color-white, $--color-primary, 80%) !default; /* d9ecff */
    $--color-primary-light-9: mix($--color-white, $--color-primary, 90%) !default; /* ecf5ff */
    
    $--color-success: #67c23a !default;
    $--color-warning: #e6a23c !default;
    $--color-danger: #f56c6c !default;
    $--color-info: #909399 !default;
    
    ...
    ¶修改变量
    直接编辑 element-variables.scss 文件,例如修改主题色为红色。
    
    $--color-primary: red;
    ¶编译主题
    保存文件后,到命令行里执行 et 编译主题,如果你想启用 watch 模式,实时编译主题,增加 -w 参数;如果你在初始化时指定了自定义变量文件,则需要增加 -c 参数,并带上你的变量文件名
    
    et
    
    > ✔ build theme font
    > ✔ build element theme
    ¶引入自定义主题
    默认情况下编译的主题目录是放在 ./theme 下,你可以通过 -o 参数指定打包目录。像引入默认主题一样,在代码里直接引用 theme/index.css 文件即可。
    
    import '../theme/index.css'
    import ElementUI from 'element-ui'
    import Vue from 'vue'
    
    Vue.use(ElementUI)
    
    
    三、在 element-variables.scss 文件里修改 $–color-primary:#409EFF,即你想要的主题颜色。然后,执行主题编译命令生成主题(et),根目录会生成一个theme文件夹。

     四、封装动态换肤色ThemePicker.vue组件。

     

    <template>
      <el-color-picker
        class="theme-picker"
        popper-class="theme-picker-dropdown"
        v-model="theme"
        :size="size">
      </el-color-picker>
    </template>
    
    <script>
    
    const version = require('element-ui/package.json').version // element-ui version from node_modules
    const ORIGINAL_THEME = '#409EFF' // default color
    export default {
      name: 'ThemePicker',
      props: {
        default: { // 初始化主题,可由外部传入
          type: String,
          //default: '#EB815B'
          default: ""+localStorage.getItem("tremePackers")+""
        },
        size: { // 初始化主题,可由外部传入
          type: String,
          default: 'small'
        }
      },
      data() {
        return {
          chalk: '', // content of theme-chalk css
          theme: ORIGINAL_THEME,
          showSuccess: true, // 是否弹出换肤成功消息
        }
      },
      mounted() {
        if(this.default != null) {
          this.theme = this.default
          this.$emit('onThemeChange', this.theme)
          this.showSuccess = false
        }
      },
      watch: {
        theme(val, oldVal) {
          if (typeof val !== 'string') return
          const themeCluster = this.getThemeCluster(val.replace('#', ''))
          const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
          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.$emit('onThemeChange', val)
          //存入localStorage
          localStorage.setItem('tremePackers',val);
          if(this.showSuccess) {
            this.$message({
              message: '换肤成功',
              type: 'success'
            })
          } else {
            this.showSuccess = true
          }
        }
      },
      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>
    
    <style>
    .theme-picker .el-color-picker__trigger {
      vertical-align: middle;
    }
    
    .theme-picker-dropdown .el-color-dropdown__link-btn {
      display: none;
    }
    </style>

    五、直接在组件中引用

    六、换肤效果测试。

  • 相关阅读:
    成员变量、类变量、局部变量的区别
    微服务学习笔记二:Eureka服务注册发现
    微服务学习笔记一:Spring Cloud简介
    Java集合篇六:Map中key值不可重复的测试
    重写Euqals & HashCode
    Java集合篇五:HashMap
    Java集合篇四:Map的基本应用
    Java集合篇三:Vector
    Java集合篇二:LinkList
    Java集合篇一:ArrayList
  • 原文地址:https://www.cnblogs.com/provedl/p/11046112.html
Copyright © 2020-2023  润新知