vue在线动态切换主题色方案
程序员文章站
2023-09-04 22:25:31
主要原理是利用webpack插件webpack-theme-color-replacer提取相关颜色css然后根据配置动态生成替换的css具体实现步骤如下:1.添加webpack插件,新建文件webp...
主要原理是利用webpack插件webpack-theme-color-replacer提取相关颜色css然后根据配置动态生成替换的css
具体实现步骤如下:
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数组中可配置多个自定义要替换的主题色
2.在vue.config.js中添加这个插件
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 // 动态切换主题色 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.在需要的时候调用 initthemecolor初始化颜色 changethemecolor改变主题颜色
import { initthemecolor,changethemecolor } from './utils/themecolorclient' initthemecolor() changethemecolor('#f56c6c')//传入颜色格式应该为十六进制颜色值,'red'类似颜色暂不支持
具体细节请参考
到此这篇关于vue在线动态切换主题色方案的文章就介绍到这了,更多相关vue 动态切换主题内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!