您好,登錄后才能下訂單哦!
這篇文章主要介紹“Vue怎么使用Less與Scss實現主題切換”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Vue怎么使用Less與Scss實現主題切換”文章能幫助大家解決問題。
具體實現:
1、初始化vue項目
2、安裝插件:
npm install style-resources-loader -D
npm install vue-cli-plugin-style-resources-loader -D
當然也要安裝less、less-loader等插件,具體的安裝配置,請自行google
3、新建theme.less文件用于全局樣式配置。在src目錄下新建theme文件夾,在這個文件夾下新建theme.less文件。具體如下:
/src/theme/theme.less // 默認的主題顏色 @primaryColor: var(--primaryColor, #000); @primaryTextColor: var(--primaryTextColor, green); // 導出變量 :export { name: "less"; primaryColor: @primaryColor; primaryTextColor: @primaryTextColor; }
4、配置vue.config.js文件,實現全局使用變量實現換膚
const path = require("path"); module.exports = { pluginOptions: { "style-resources-loader": { preProcessor: "less", patterns: [ // 這個是加上自己的路徑,不能使用(如下:alias)中配置的別名路徑 path.resolve(__dirname, "./src/theme/theme.less"), ], }, }, };
5、具體的使用:
<template> <div class="hello"> <p>我是測試文字</p> </div> </template> <script> export default { name: "HelloWorld", }; </script> <style scoped lang="less"> .hello { p { color: @primaryTextColor; } } </style>
備注:如果是用scss也基本同以上用法,只是scss的變量名用‘$’作為前綴,less使用@
至此,我們已經實現了靜態更換皮膚,那如何實現動態換膚呢,最重要的就是以下的文件了。
我們可以多配置幾種默認主題
6、在theme文件夾下新建model.js文件,用于存放默認主題
// 一套默認主題以及一套暗黑主題 // 一套默認主題以及一套暗黑主題 export const themes = { default: { primaryColor: `${74}, ${144},${226}`, primaryTextColor: `${74}, ${144},${226}`, }, dark: { primaryColor: `${0},${0},${0}`, primaryTextColor: `${0},${0},${0}`, }, };
7、實現動態切換:
在/src/theme文件夾下新建theme.js文件,代碼如下:
import { themes } from "./model"; // 修改頁面中的樣式變量值 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); // 保存主題到本地,下次進入使用該主題 const themeConfig = themes[themeName]; // 如果有主題名稱,那么則采用我們定義的主題 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')
1、一般elementUI主題色都有這樣一個文件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文件,用于頁面基礎設置
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、一般換膚都是需要有個顏色選擇器,用于皮膚設置
在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組件的位置,去調用vuex中的changeSetting函數
<theme-picker @change="themeChange" /> import ThemePicker from '@/components/ThemePicker' export default { components: { ThemePicker }, methods:{ themeChange(val) { this.$store.dispatch('settings/changeSetting', { key: 'theme', value: val }) } } }
關于“Vue怎么使用Less與Scss實現主題切換”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。