ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

element ui+vue2.0实现换肤并且自身写的颜色也可以

2021-04-27 20:01:58  阅读:185  来源: 互联网

标签:换肤 blue style const green element ui link red


问题:本地环境换肤可以,但是打包后发现自己写的主题色值#409eff,并没有被替换成功,只有element ui自身的主题色替换了

主要代码如下:

//watch监听主题色变化
theme: {
      async handler(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: '主题色切换中...',
          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()
        /**++++++++++++++++++++++++++++++++++++++++++++++++ */
        //为解决生产环境中切换主题色失败
        if (!this.flag && process.env.NODE_ENV === 'production') {
          //判断是否是第一次打开页面
          this.flag = true
          ;[].slice
            .call(document.querySelectorAll('link')) //获取所有的link链接
            .forEach(async (item) => {
              if (item.rel === 'stylesheet' || item.as === 'style') {
                //判断是否是 css
                const { data } = await axios.get(item.href) // 重新获取到 css 的内容
                if (
                  new RegExp(oldVal, 'i').test(data) && // 判断是否需要换肤
                  !/Chalk Variables/.test(data) // 判断是否是 element-ui 的 css 前面已经进行处理了这里忽略
                ) {
                  item.remove() // 移出 link
                  const style = document.createElement('style') // 创建 style
                  style.innerText = data // 把 link 的内容添加到 style 标签中
                  // 更新背景图会导致路径错误,忽略更新。
                  style.innerText = data.replace(
                    /url\(..\/..\/static/g,
                    'url(static'
                  )
                  style.isAdd = true // 为后面判断是否是 link 生成的style,方便标识加入到头部head中
                  styles.push(style)
                  this.stylesRender(styles, originalCluster, themeCluster) // 样式渲染
                }
              }
            })
        }
        /**++++++++++++++++++++++++++++++++++++++++++++++++ */
        // 筛选需要修改的style
        const styles = [].slice
          .call(document.querySelectorAll('style'))
          .filter((style) => {
            const text = style.innerText
            return (
              new RegExp(oldVal, 'i').test(text) &&
              !/Chalk Variables/.test(text)
            )
          })
        this.styleRender(styles, originalCluster, themeCluster)
        this.$emit('change', val)

        $message.close()
      },
      immediate: true,
    },
     // 遍历修改所有需修改的style
    styleRender(styles, originalCluster, themeCluster) {
      styles.forEach((style) => {
        const { innerText } = style
        if (typeof innerText !== 'string') return
        style.innerText = this.updateStyle(
          innerText,
          originalCluster,
          themeCluster
        )
        //打包后的link转换的style
        if (style.isAdd) {
          // 如果是通过 link 创建的style 就添加到head中
          style.isAdd = false
          document.head.appendChild(style)
        }
      })
    },
    //更新 <style>
     updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },
	//修改lin引入的css
    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
    },

为了解决上面的问题:我主要加的代码在加注释那一块,上面的问题出现的原因在于,
1、打包后的css为link形式,而我的换肤时主要筛选的是style样式,然后进行替换。因此我判断是否是生产环境并且是第一次进来,然后将link样式转为style,通过axios请求获得link下的内容,成功后移除了link,创建style,并把获得的内容赋予给style

item.remove() // 移出 link
const style = document.createElement('style') // 创建 style
style.innerText = data // 把 link 的内容添加到 style 标签中

2、然后我打了一个包,发现我的自己写的颜色值#409eff都被换成我想要的主题色,但是另一个问题来了,我的背景图片加载失败了。我去f12看了下,我的图片路径变成了…/…/static。于是我只能在转换style的时候手动的改下路径

// 更新背景图会导致路径错误,忽略更新。
style.innerText = data.replace(/url\(..\/..\/static/g,'url(static')

3、再次打了一个包,终于都可以正常显示了,真的是坎坷。

标签:换肤,blue,style,const,green,element,ui,link,red
来源: https://blog.csdn.net/weixin_45524020/article/details/116207984

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有