vue中使用Element主题自定义肤色

一、搭建好项目的环境。

二、根据ElementUI官网的自定义主题(http://element.eleme.io/#/zh-CN/component/custom-theme)来安装【主题生成工具】。

三、在 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/[email protected]${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>

五、直接在组件中引用

六、换肤效果测试。(关闭浏览器再次打开依旧是你所选中的主题肤色)

原文地址:https://www.cnblogs.com/dengqichang/p/10364455.html

时间: 2024-07-30 20:25:08

vue中使用Element主题自定义肤色的相关文章

vue中对element的弹框messagebox的二次封装

在vue中对确认框的二次封装 使用场景:在页面中做某些需要警告的操作时的弹框提示 1.在utils文件夹下新建一个confirm.js文件来对messageBox的封装,内容如下: /** confirm.js */ import { MessageBox } from 'element-ui' export function handleCofirm(text = '确定执行此操作吗?', type = 'warning') { return MessageBox.confirm(text,

vue中使用element来创建目录列表

之前按照项目需求使用element中的tree来创建目录列表,如今记录一下. 一.项目需求 1.完整展示目录列表 2.右击节点选择重命名,删除,创建文件夹三个选项 3.拖拽文件夹,其中拖拽文件夹有以下要求: a. 如果该文件夹内已存在上传文件,则其他文件夹不能拖拽进入该文件夹内 b.整个目录中有且仅有一个根目录,拖拽文件夹的范围只能在该根目录里面 4.重命名文件夹要求: a.重命名完成后按enter键完成 5.删除文件夹要求: a.如果该文件夹内已含有上传文件,则删除失败 6.创建文件夹要求:

vue中自定义指令

在vue中自定义标签,首先要调用vue中一个directive的方法,具体方法:Vue.direction('指令名称',function(){ }); 例如我们要写一个关于颜色的指令,叫v-colorred: 1 Vue.directive('colorred',function(){ 2 3 this.el.style.color='red'; 4 }); 在html中,我直接用v-colorred指令就可以了,例如: 1 <p v-colorred>1234567890</p>

vue中自定义组件(插件)

vue中自定义组件(插件) 原创 2017年01月04日 22:46:43 标签: 插件 在vue项目中,可以自定义组件像vue-resource一样使用Vue.use()方法来使用,具体实现方法: 1.首先建一个自定义组件的文件夹,比如叫loading,里面有一个index.js,还有一个自定义组件loading.vue,在这个loading.vue里面就是这个组件的具体的内容,比如: <template> <div> loading.............. </div

在Vue框架中引入Element

文章会讲到如何在Vue框架中引入Element 那我们先来说一下Vue框架:Vue是渐进式,JavaScript框架.很多人不理解什么是渐进式,简单点讲就是易用.灵活.高效(没有太多限制) 这里介绍npm安装方式: 打开cmd,找到你Vue项目的路径 运行 npm i element-ui -S 然后在main.js里写入以下内容: import Vue from 'vue'; import ElementUI from 'element-ui'; import 'element-ui/lib/

如何在vue项目中引入element ui组件

(1)安装element ui,即: npm i element-ui -S 然后在项目中的node_modules目录下查看是否有element-ui文件夹,如果有说明安装成功了: (2)引入element ui 在main.js中引入element ui,即: 1 import ElementUI from 'element-ui' 2 import 'element-ui/lib/theme-chalk/index.css' 3 Vue.use(ElementUI) [注意红色部分,以前是

vue中的v-model原理,与组件自定义v-model

VUE中的v-model可以实现双向绑定,但是原理是什么呢?往下看看吧 根据官方文档的解释,v-model其实是一个语法糖,它会自动的在元素或者组件上面解析为 :value="" 和 @input="", 就像下面这样 1 // 标准写法 2 <input v-model="name"> 3 4 // 等价于 5 <input :value="name" @input="name = $event.

对vue中的computed属性,watch监听,计算属性理解

自己的理解: computed用来监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义,然后就可以在页面上进行双向数据绑定展示出结果或者用作其他处理: computed比较适合对多个变量或者对象进行处理后返回一个结果值,也就是数多个变量中的某一个值发生了变化则我们监控的这个值也就会发生变化,举例:购物车里面的商品列表和总金额之间的关系,只要商品列表里面的商品数量发生变化,或减少或增多或删除商品,总金额都应该发生变化.这里的这个总金额使用computed属性来进行计算是最

vue中template的三种写法

第一种(使用模板字符串)早期字符串拼接年代 <div id="app"></div> new Vue({ el: "#app", template: '<div> <h1>{{message}}</h1> <div>', data: { message: '字符串拼接' } }) 第二种(使用script元素)HTML5标准之前的写法 <div id="app">