您好,登錄后才能下訂單哦!
主要原理是利用webpack插件webpack-theme-color-replacer提取相關(guān)顏色css然后根據(jù)配置動(dòng)態(tài)生成替換的css
具體實(shí)現(xiàn)步驟如下:
1.添加webpack插件,新建文件webpack/themePlugin.js
const ThemeColorReplacer = require('webpack-theme-color-replacer') const forElementUI = require('webpack-theme-color-replacer/forElementUI') const config = require('../src/config/appConfig') module.exports = new ThemeColorReplacer({ fileName: 'css/theme-colors.[contenthash:8].css', matchColors: [ ...forElementUI.getElementUISeries(config.themeColor), //element-ui主色系列 // '#0cdd3a', //自定義顏色 ], changeSelector: forElementUI.changeSelector, isJsUgly: process.env.NODE_ENV !== 'development', // injectCss: false, // resolveCss(resultCss) { // optional. Resolve result css code as you wish. // return resultCss + youCssCode // } })
matchColors數(shù)組中可配置多個(gè)自定義要替換的主題色
2.在vue.config.js中添加這個(gè)插件
const themePlugin=require('./webpack/themePlugin'); module.exports = { configureWebpack: { plugins: [ themePlugin ] } }
3.新建文件themeColorClient.js
import client from 'webpack-theme-color-replacer/client' import forElementUI from 'webpack-theme-color-replacer/forElementUI' import appConfig from '@/config/appConfig' export let curColor = appConfig.themeColor // 動(dòng)態(tài)切換主題色 export function changeThemeColor(newColor) { var options = { newColors: [...forElementUI.getElementUISeries(newColor)], } return client.changer.changeColor(options, Promise) .then(() => { curColor = newColor localStorage.setItem('theme_color', curColor) }); } export function initThemeColor() { const savedColor = localStorage.getItem('theme_color') if (savedColor) { curColor = savedColor changeThemeColor(savedColor) } }
4.在需要的時(shí)候調(diào)用 initThemeColor初始化顏色 changeThemeColor改變主題顏色
import { initThemeColor,changeThemeColor } from './utils/themeColorClient' initThemeColor() changeThemeColor('#F56C6C')//傳入顏色格式應(yīng)該為十六進(jìn)制顏色值,'red'類似顏色暫不支持
具體細(xì)節(jié)請(qǐng)參考https://github.com/hzsrc/vue-element-ui-scaffold-webpack4
到此這篇關(guān)于vue在線動(dòng)態(tài)切換主題色方案的文章就介紹到這了,更多相關(guān)vue 動(dòng)態(tài)切換主題內(nèi)容請(qǐng)搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。