• vue+element-ui实现主题切换


    element-ui提供了自定义主题 自定义主题

    一、安装

    • npm i element-theme -g

    • npm i element-theme-chalk -D

    • npm i https://github.com/ElementUI/theme-chalk -D

    • 官网说明安装完成后需要et -i并会有element-variables.scss文件,但是我文件中并未找到 node_modules/.bin/et,所以手动生成了

    • 下图element-variables.scss是自己写的,因为安装完成后并未生成此文件
      在这里插入图片描述

    • 文件中让内容如下`/* 改变主题色变量 */

       ```
       /* 改变主题色变量,设置完成后会有按钮字体等组件会变化 */
       $--color-primary: #d85f6a;  
       
       /* 改变 icon 字体路径变量,必需 */
       $--font-path: '~element-ui/lib/theme-chalk/fonts';
       
       @import "~element-ui/packages/theme-chalk/src/index";
       ```
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9

    页面文件:index.vue

         <el-radio-group v-model="themeRadio" @change="changeClick" size="mini">
           <el-radio label="#d85f6a">红色主题</el-radio>
              <el-radio label="#409EFF">蓝色主题</el-radio>
          </el-radio-group>
    	
    	文件引入:
    	import ColorPicker from "@/layout/colorpicker/index";  
    	使用:
        <color-picker :colorVal="colorVal"></color-picker>
    	方法:
        changeClick(value){
          this.colorVal = value
          localStorage.setItem('skin',value)
          this.$store.commit("setSkin",value)
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

    • colorpicker.vue文件,文件内容如下:
    <template>
      <el-color-picker
        v-if="false"
        v-model="theme"
        :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
        class="theme-picker"
        popper-class="theme-picker-dropdown"
      />
    </template>
    <script>
    
    const version = require('element-ui/package.json').version // element-ui version from node_modules
    const ORIGINAL_THEME = '#409EFF' // default color
    import { Loading } from 'element-ui';
    export default {
      props:{   //在页面中将colorVal传进来
        colorVal:{
          type:String,  
        }
      },
      created(){
        // let option={
        //   background:'#FFFFFF'
        // }
          this.loadingInstance =Loading.service();  //这里增加加载loadding,因为刷新页面会出现延迟
    
      },
      data() {
        return {
          chalk: '', // content of theme-chalk css
          theme: '',
          loadingInstance:true
        }
      },
      computed: {
        defaultTheme() {
        // 将选择的颜色属性保存在vuex中,如果页面刷新娶不到就从ocalStorage中取
          if(this.$store.state.skin)  return this.$store.state.skin;
          else return  localStorage.getItem('skin')
          // return this.$store.state.skin
        }
      },
      watch: {
        defaultTheme:{
          handler: function(val) {
            this.$nextTick(() => {
              // this.$emit('input', this.model);
            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('#', ''))
          const $message = this.$message({
            message: '  Compiling the theme',
            customClass: 'theme-message',
            type: 'success',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          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)
          $message.close()
          // this.$message({
          //     message:'皮肤切换成功',
          //     type:'success'
          // })
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            // this.loadingInstance.close();
          })
          setTimeout(()=>{
            this.loadingInstance.close();
    
          },1000)
        }
      },
      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()
          })
        },
    
        //将传入的24进制颜色标号进行处理,
        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-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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186

    效果:
    红色主题
    蓝色主题

    但是到现在有个问题,就是element-ui有自己的ui主题,每次radio切换主题时没问题,但是F5刷新后页面元素颜色会闪烁,顺序:element-ui颜色>当前设置缓存颜色,为了解决这个问题,就优化了代码,在APP.vue中设置,当页面刷新时能更快的渲染
    1.新建colorpicker.js文件
    在这里插入图片描述
    2.APP.vue中引入

    //colorpicker.js中只保留了 colorpicker.vue 中 methods:中的方法
    import  colorpicker from '@/mixins/colorpicker.js'
    
    • 1
    • 2

    3.使用mixins模式

    mixins:[colorpicker],
    
    • 1

    在created中使用

      async created() {
          await this.getColor('#409EFF')
          await this.configRouter();
      },
      //将colorpicker.vue中此方法拿出来
      async getColor(val){
          let theme = val
          const oldVal = this.chalk ? theme : ORIGINAL_THEME
          if (typeof val !== 'string') return
          const themeCluster = this.getThemeCluster(val.replace('#', ''))
          const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
          const $message = this.$message({
            message: '  Compiling the theme',
            customClass: 'theme-message',
            type: 'success',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          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)
          $message.close()
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
  • 相关阅读:
    Linux: command: cpio
    详细介绍R语言在数据分析中的应用
    数据科学 - 数据可视化(持续更新)
    Latex分点自我记录
    Android:关于定时任务重启之后的问题研究
    【机器学习基础】正则化
    数据库管理-第159期 Oracle Vector DB & AI-10(20240311)
    AIX 7.2 虚拟机 bash安装及 Aix 文件名补齐 使用优化篇
    Java系列 超简单说人话的 异常类详细讲解 Exception MyExcepyion try catch语句
    深度解读汽车域控制器
  • 原文地址:https://blog.csdn.net/webshao/article/details/125440269