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

Vue使用Less與Scss實(shí)現(xiàn)主題切換方法詳細(xì)講解

 更新時(shí)間:2023年02月25日 09:33:18   作者:苪玫兒呀  
目前,在眾多的后臺(tái)管理系統(tǒng)中,換膚功能已是一個(gè)很常見(jiàn)的功能。用戶(hù)可以根據(jù)自己的喜好,設(shè)置頁(yè)面的主題,從而實(shí)現(xiàn)個(gè)性化定制。目前,我所了解到的換膚方式,也是我目前所掌握的兩種換膚方式,想同大家一起分享

一、Less/Scss變量換膚

具體實(shí)現(xiàn):

1、初始化vue項(xiàng)目

2、安裝插件:

npm install style-resources-loader -D

npm install vue-cli-plugin-style-resources-loader -D

當(dāng)然也要安裝less、less-loader等插件,具體的安裝配置,請(qǐng)自行g(shù)oogle

3、新建theme.less文件用于全局樣式配置。在src目錄下新建theme文件夾,在這個(gè)文件夾下新建theme.less文件。具體如下:

/src/theme/theme.less
// 默認(rèn)的主題顏色
@primaryColor: var(--primaryColor, #000);
@primaryTextColor: var(--primaryTextColor, green);
// 導(dǎo)出變量
:export {
  name: "less";
  primaryColor: @primaryColor;
  primaryTextColor: @primaryTextColor;
}

4、配置vue.config.js文件,實(shí)現(xiàn)全局使用變量實(shí)現(xiàn)換膚

const path = require("path");
module.exports = {
  pluginOptions: {
    "style-resources-loader": {
      preProcessor: "less",
      patterns: [
        // 這個(gè)是加上自己的路徑,不能使用(如下:alias)中配置的別名路徑
        path.resolve(__dirname, "./src/theme/theme.less"),
      ],
    },
  },
};

5、具體的使用:

<template>
  <div class="hello">
    <p>我是測(cè)試文字</p>
  </div>
</template>
<script>
export default {
  name: "HelloWorld",
};
</script>
<style scoped lang="less">
.hello {
  p {
    color: @primaryTextColor;
  }
}
</style>

備注:如果是用scss也基本同以上用法,只是scss的變量名用‘$’作為前綴,less使用@

至此,我們已經(jīng)實(shí)現(xiàn)了靜態(tài)更換皮膚,那如何實(shí)現(xiàn)動(dòng)態(tài)換膚呢,最重要的就是以下的文件了。

我們可以多配置幾種默認(rèn)主題

6、在theme文件夾下新建model.js文件,用于存放默認(rèn)主題

// 一套默認(rèn)主題以及一套暗黑主題
// 一套默認(rèn)主題以及一套暗黑主題
export const themes = {
  default: {
    primaryColor: `${74}, ${144},${226}`,
    primaryTextColor: `${74}, ${144},${226}`,
  },
  dark: {
    primaryColor: `${0},${0},${0}`,
    primaryTextColor: `${0},${0},${0}`,
  },
};

7、實(shí)現(xiàn)動(dòng)態(tài)切換:

在/src/theme文件夾下新建theme.js文件,代碼如下:

import { themes } from "./model";
// 修改頁(yè)面中的樣式變量值
const changeStyle = (obj) => {
  for (let key in obj) {
    document
      .getElementsByTagName("body")[0]
      .style.setProperty(`--${key}`, obj[key]);
  }
};
// 改變主題的方法
export const setTheme = (themeName) => {
  localStorage.setItem("theme", themeName); // 保存主題到本地,下次進(jìn)入使用該主題
  const themeConfig = themes[themeName];
  // 如果有主題名稱(chēng),那么則采用我們定義的主題
  if (themeConfig) {
    localStorage.setItem("primaryColor", themeConfig.primaryColor); // 保存主題色到本地
    localStorage.setItem("primaryTextColor", themeConfig.primaryTextColor); // 保存文字顏色到本地
    changeStyle(themeConfig); // 改變樣式
  } else {
    let themeConfig = {
      primaryColor: localStorage.getItem("primaryColor"),
      primaryTextColor: localStorage.getItem("primaryTextColor"),
    };
    changeStyle(themeConfig);
  }
};

8、切換主題

this.setTheme('dark')

二、element-UI組件的換膚

1、一般elementUI主題色都有這樣一個(gè)文件element-variables.scss:

/**
* I think element-ui's default theme color is too light for long-term use.
* So I modified the default color and you can modify it to your liking.
**/
/* theme color */
$--color-primary: #1890ff;
$--color-success: #13ce66;
$--color-warning: #ffba00;
$--color-danger: #ff4949;
// $--color-info: #1E1E1E;
$--button-font-weight: 400;
// $--color-text-regular: #1f2d3d;
$--border-color-light: #dfe4ed;
$--border-color-lighter: #e6ebf5;
$--table-border: 1px solid #dfe6ec;
/* icon font path, required */
$--font-path: "~element-ui/lib/theme-chalk/fonts";
@import "~element-ui/packages/theme-chalk/src/index";
// the :export directive is the magic sauce for webpack
// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass
:export {
  theme: $--color-primary;
}

2、main.js中引用

import './styles/element-variables.scss'

3、在store文件夾下新建settings.js文件,用于頁(yè)面基礎(chǔ)設(shè)置

import variables from '@/styles/element-variables.scss'
const state = {
  theme: variables.theme
}
const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  }
}
const actions = {
  changeSetting({ commit }, data) {
    commit('CHANGE_SETTING', data)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

4、一般換膚都是需要有個(gè)顏色選擇器,用于皮膚設(shè)置

在src目錄下新建ThemePicker文件夾,新建index.vue文件。

<template>
  <el-color-picker
    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
export default {
  data() {
    return {
      chalk: '', // content of theme-chalk css
      theme: ''
    }
  },
  computed: {
    defaultTheme() {
      return this.$store.state.settings.theme
    }
  },
  watch: {
    defaultTheme: {
      handler: function(val, oldVal) {
        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('#', ''))
      console.log(themeCluster, originalCluster)
      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()
    }
  },
  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()
      })
    },
    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>

5、在使用ThemePicker組件的位置,去調(diào)用vuex中的changeSetting函數(shù)

 <theme-picker style="float: right;height: 26px;margin: -3px 8px 0 0;" @change="themeChange" />
import ThemePicker from '@/components/ThemePicker'
export default {
  components: { ThemePicker },
methods:{
  themeChange(val) {
      this.$store.dispatch('settings/changeSetting', {
        key: 'theme',
        value: val
      })
    }
}
}

至此,就可以實(shí)現(xiàn)elementUI組件的換膚功能了

總結(jié):其實(shí)上邊兩種方式換膚的實(shí)現(xiàn)思路都差不多,下邊那篇自己理解得不是很好,歡迎補(bǔ)充

到此這篇關(guān)于Vue使用Less與Scss實(shí)現(xiàn)主題切換方法詳細(xì)講解的文章就介紹到這了,更多相關(guān)Vue主題切換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Vue3中使用reactive時(shí),后端有返回?cái)?shù)據(jù)但dom沒(méi)有更新的解決

    Vue3中使用reactive時(shí),后端有返回?cái)?shù)據(jù)但dom沒(méi)有更新的解決

    這篇文章主要介紹了Vue3中使用reactive時(shí),后端有返回?cái)?shù)據(jù)但dom沒(méi)有更新的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Vue3插槽(slot)使用方法詳解

    Vue3插槽(slot)使用方法詳解

    在VUE開(kāi)發(fā)項(xiàng)目的過(guò)程中,插槽<slot>是重要的承載分發(fā)內(nèi)容的出口,下面這篇文章主要給大家介紹了關(guān)于Vue3插槽(slot)使用的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-11-11
  • Vuejs第十三篇之組件——雜項(xiàng)

    Vuejs第十三篇之組件——雜項(xiàng)

    組件(Component)是 Vue.js 最強(qiáng)大的功能之一。本文重點(diǎn)給大家介紹vuejs組件相關(guān)知識(shí),非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧
    2016-09-09
  • vue源碼解析computed多次訪問(wèn)會(huì)有死循環(huán)原理

    vue源碼解析computed多次訪問(wèn)會(huì)有死循環(huán)原理

    這篇文章主要為大家介紹了vue源碼解析computed多次訪問(wèn)會(huì)有死循環(huán)原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • vue子組件如何使用父組件傳過(guò)來(lái)的值

    vue子組件如何使用父組件傳過(guò)來(lái)的值

    這篇文章主要介紹了vue子組件如何使用父組件傳過(guò)來(lái)的值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • Vue中使用JsonView來(lái)展示Json樹(shù)的實(shí)例代碼

    Vue中使用JsonView來(lái)展示Json樹(shù)的實(shí)例代碼

    這篇文章主要介紹了Vue之使用JsonView來(lái)展示Json樹(shù)的實(shí)例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Vue.js做select下拉列表的實(shí)例(ul-li標(biāo)簽仿select標(biāo)簽)

    Vue.js做select下拉列表的實(shí)例(ul-li標(biāo)簽仿select標(biāo)簽)

    下面小編就為大家分享一篇Vue.js做select下拉列表的實(shí)例(ul-li標(biāo)簽仿select標(biāo)簽),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03
  • Vue監(jiān)聽(tīng)頁(yè)面刷新和關(guān)閉功能

    Vue監(jiān)聽(tīng)頁(yè)面刷新和關(guān)閉功能

    我在做項(xiàng)目的時(shí)候,有一個(gè)需求,在離開(kāi)(跳轉(zhuǎn)或者關(guān)閉)購(gòu)物車(chē)頁(yè)面或者刷新購(gòu)物車(chē)頁(yè)面的時(shí)候向服務(wù)器提交一次購(gòu)物車(chē)商品數(shù)量的變化。這篇文章主要介紹了vue監(jiān)聽(tīng)頁(yè)面刷新和關(guān)閉功能,需要的朋友可以參考下
    2019-06-06
  • 關(guān)于Vue.nextTick()的正確使用方法淺析

    關(guān)于Vue.nextTick()的正確使用方法淺析

    最近在項(xiàng)目中遇到了一個(gè)需求,我們通過(guò)Vue.nextTick()來(lái)解決這一需求,但發(fā)現(xiàn)網(wǎng)上這方面的資料較少,所以自己來(lái)總結(jié)下,下面這篇文章主要給大家介紹了關(guān)于Vue.nextTick()正確使用方法的相關(guān)資料,需要的朋友可以參考下。
    2017-08-08
  • 詳解Vue + Vuex 如何使用 vm.$nextTick

    詳解Vue + Vuex 如何使用 vm.$nextTick

    這篇文章主要介紹了詳解Vue + Vuex 如何使用 vm.$nextTick,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-11-11

最新評(píng)論