欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue+element-ui實(shí)現(xiàn)主題切換功能

 更新時(shí)間:2022年06月26日 10:33:09   作者:邵先森~  
這篇文章主要介紹了vue+element-ui實(shí)現(xiàn)主題切換功能,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

element-ui提供了自定義主題 自定義主題

一、安裝

  • npm i element-theme -g
  • npm i element-theme-chalk -D
  • npm i https://github.com/ElementUI/theme-chalk -D
  • 官網(wǎng)說明安裝完成后需要et -i并會(huì)有element-variables.scss文件,但是我文件中并未找到 node_modules/.bin/et,所以手動(dòng)生成了

下圖element-variables.scss是自己寫的,因?yàn)榘惭b完成后并未生成此文件

文件中讓內(nèi)容如下`/* 改變主題色變量 */

 ```
 /* 改變主題色變量,設(shè)置完成后會(huì)有按鈕字體等組件會(huì)變化 */
 $--color-primary: #d85f6a;  
 
 /* 改變 icon 字體路徑變量,必需 */
 $--font-path: '~element-ui/lib/theme-chalk/fonts';
 
 @import "~element-ui/packages/theme-chalk/src/index";
 ```

頁面文件:index.vue

     <el-radio-group v-model="themeRadio" @change="changeClick" size="mini">
       <el-radio label="#d85f6a">紅色主題</el-radio>
          <el-radio label="#409EFF">藍(lán)色主題</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)
    },

colorpicker.vue文件,文件內(nèi)容如下:

<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傳進(jìn)來
    colorVal:{
      type:String,  
    }
  },
  created(){
    // let option={
    //   background:'#FFFFFF'
    // }
      this.loadingInstance =Loading.service();  //這里增加加載loadding,因?yàn)樗⑿马撁鏁?huì)出現(xiàn)延遲

  },
  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(() => { // 以服務(wù)的方式調(diào)用的 Loading 需要異步關(guān)閉
        // 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進(jìn)制顏色標(biāo)號(hào)進(jìn)行處理,
    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>

效果:

但是到現(xiàn)在有個(gè)問題,就是element-ui有自己的ui主題,每次radio切換主題時(shí)沒問題,但是F5刷新后頁面元素顏色會(huì)閃爍,順序:element-ui顏色>當(dāng)前設(shè)置緩存顏色,為了解決這個(gè)問題,就優(yōu)化了代碼,在APP.vue中設(shè)置,當(dāng)頁面刷新時(shí)能更快的渲染
1.新建colorpicker.js文件

2.APP.vue中引入

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

3.使用mixins模式

mixins:[colorpicker],

在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()
    },

到此這篇關(guān)于vue+element-ui實(shí)現(xiàn)主題切換的文章就介紹到這了,更多相關(guān)vue主題切換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論