需求:根据element的自定义主题色,之后改变element的全局所有颜色,解决页面刷新后主题色失效问题,这个需要把颜色存入到浏览器的存储中,如果换个浏览器就得重新选择了哈,如果需要在不同的浏览器保持一致的主题,需要跟后端沟通
之前还写过一个简单的,有需要的可以去看:vue实现element-ui自定义主题色切换(简单版)_element主题切换_请叫我欧皇i的博客-CSDN博客
效果如下:
1.下载颜色插件
我下的是1.4.6版本,最好下载的版本一致吧,不然报错了我也没办法
npm install webpack-theme-color-replacer@1.4.6
2.建个js文件themeColorClient.js
直接复制粘贴以下代码
import client from 'webpack-theme-color-replacer/client'
import forElementUI from 'webpack-theme-color-replacer/forElementUI'
// 注意自己项目里的引入路径export let curColor = '#409EFF'// 动态切换主题色
export function changeThemeColor(newColor) {var options = {newColors: [...forElementUI.getElementUISeries(newColor), '#ff0000', '#ffff00']}return client.changer.changeColor(options, Promise).then(() => {curColor = newColorlocalStorage.setItem('theme_color', curColor)})
}
// 页面刷新的时候会触发
export function initThemeColor() {const savedColor = localStorage.getItem('theme_color')if (savedColor) {curColor = savedColorchangeThemeColor(savedColor)}
}
3.在main.js文件导入
保证每次刷新数据还在
import { initThemeColor } from './plugins/themeColorClient'
initThemeColor()
4.颜色选择器
<template><el-color-picker v-model="mainColor" size="small" @change="changeColor" />
</template><script>
import { changeThemeColor, curColor } from "@/plugins/themeColorClient";
export default {name: "d2-header-color",data() {return {mainColor: curColor,predefine: ["#ff4500","#ff8c00","#ffd700","#90ee90","#00ced1","#1e90ff","#c71585",],};},methods: {changeColor(newColor) {console.log(newColor, "颜色");changeThemeColor(newColor).then((t) => console.log("123465")).catch((err) => console.log(err, "567"));//.then(t => this.$x.toast.success('主题色切换成功~'))},},
};
</script>
5.在vue.config.js中配置
const ThemeColorReplacer = require('webpack-theme-color-replacer')
const forElementUI = require('webpack-theme-color-replacer/forElementUI')
module.exports = {chainWebpack: config => {// 自定义主题色config.plugin('theme-color-replacer').use(ThemeColorReplacer, [{fileName: 'style/theme-colors.[contenthash:8].css',matchColors: [...forElementUI.getElementUISeries(process.env.VUE_APP_ELEMENT_COLOR), // Element-ui主色系列'#0cdd3a', // 自定义颜色'#c655dd'],changeSelector: forElementUI.changeSelector,// 解决history模式下路由跳转样式不生效问题injectCss: true,isJsUgly: process.env.NODE_ENV === 'production' ? true : undefined}])
}}
这样就可以实现了,文章到此结束,希望对你有所帮助~有不懂的可以在评论区联系我