有时候一个项目的主题并不能满足所有人的审美,这时候换肤功能就很友好,本项目基于vue+element实现后台管理项目的换肤功能

1.创建换肤组件

<template>
  <el-color-picker
    class="theme-picker"
    popper-class="theme-picker-dropdown"
    v-model="theme"
    :predefine="predefinecolors"
  ></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: '#2668b1'
      // default: `${localstorage.getitem("tremepackers")==null?"#c60404":localstorage.getitem("tremepackers")}`
    }
    // size: { // 初始化主题,可由外部传入
    //   type: string,
    //   default: 'small'
    // },
  },
  data() {
    return {
      chalk: "", // content of theme-chalk css
      theme: original_theme,
      showsuccess: true, // 是否弹出换肤成功消息
      predefinecolors: [
        "#2668b1",
        "#52b493",
        "#429798",
        "#32789c",
        "#1944a5",
        "#5944bc",
        "#995dcd",
        "#ce7e5b",
        "#ee8b9b",
        "#283551"
      ]
    };
  },
  mounted() {
    this.theme = this.defaulttheme;
    // this.$emit('onthemechange', this.theme)
    this.showsuccess = true;
  },
  computed: {
    defaulttheme() {
      return this.$store.state.theme;
    }
  },
  watch: {
    async 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)
                document
                  .getelementsbytagname("style")[0]
                  .insertbefore(styletag, null);
              }
              styletag.innertext = newstyle;
            };
          };
 
          const chalkhandler = gethandler("chalk", "chalk-style");
 
          if (!this.chalk) {
            const url = `../../assets/style/theme/index.css`;//本地css样式地址
            // const url = `./dist/index.css`;//项目打包后css地址(原文件放入public文件夹中)
            // 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.$store.commit("themcolor", val);//将更换的颜色存入store
          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;
}
.el-color-picker--small .el-color-picker__trigger {
  border: none;
}
</style>

上面这块代码值得注意,红框里的代码是在head里所有节点后插入一个新的style标签,打包后优先级较高,但有个问题,有些地方的颜色直接消失变成空白影响了样式,于是改成绿框里的代码,但绿框里的代码打包后优先级会低于原来样式颜色的而优先级,所以需要根据项目调样式优先级

这块的代码也需要注意,如果公司直接使用的外网那么直接使用第三个url就行,如果公司使用的内网访问不了外部网页那么可以通过第三条url下载项目对应element版本的css样式,把css文件放到项目里,但要注意放到不会被编译的问价夹里,我项目用的是vue cli4,所以我动态转换的css文件放在public文件夹里,放到assets问价夹中样式文件会被编译,因而路径会报404,并且这块使用的url是文件打包编译后样式的路径,这是值得注意的地方

2.如果项目中有的样式颜色没有用到element,可以把颜色缓存到vuex里,然后在具体逐渐里通过计算属性获取再在样式上动态绑定

vuex:

使用的组件中:

到此这篇关于vue+element实现动态换肤的示例代码的文章就介绍到这了,更多相关vue+element动态换肤内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!