前景提要:要求不同权限账号登录侧边栏颜色不一样。分为 theme:1代表默认样式,theme:2代表深色主题样式。
1.首先定义一个主题文件 theme.js,定义两个主题样式
// 主要是切换菜单栏和菜单头部主题的设计,整体主题样式切换是否能匹配
export const _Theme = {'lightTheme': {// 默认主题样式,要和varibles.scss的变量参数属性一样,theme为1menuBg: '#ffffff',menuText: '#464646',subMenuActiveText: '#464646',menu: '#F7FCFF'},'darkTheme': {// 深色主题,theme为2menuBg: '#2781AB',menuText: '#BDCBD9',subMenuActiveText: '#ffffff',menu: '#106E9A'}
}
2.在 App.vue 里获取上边的 js 文件的主题
App.vue :
<template><div id="app"><router-view /></div>
</template><script>
import { _Theme } from './theme.js'
export default {name: 'App',computed: {nowTheme: {get() {return this.$store.state.user.user.theme}}},watch: {// 主题切换nowTheme() {if (this.nowTheme === 2) {this.changeStyle(_Theme.darkTheme)} else {this.changeStyle(_Theme.lightTheme)}}},methods: {//主要代码changeStyle(obj) {for (const key in obj) {document.getElementsByTagName('body')[0].style.setProperty(`--${key}`, obj[key])}}}}
</script>
侧边栏文件:index.vue:```javascript
<template><el-scrollbar wrap-class="scrollbar-wrapper"><el-menu:default-active="activeMenu":collapse="isCollapse":background-color="variablesa.menuBg":text-color="variablesa.menuText":unique-opened="$store.state.settings.uniqueOpened":active-text-color="variablesa.menuActiveText":collapse-transition="false"mode="vertical"><sidebar-itemv-for="route in sidebarRouters":key="route.path":item="route":base-path="route.path"/></el-menu></el-scrollbar>
</template><script>
import SidebarItem from './SidebarItem'
import variables from '@/assets/styles/variables.scss' //主要代码export default {computed: {variablesa() {return variables}}
}
</script>
侧边栏样式表:variables.scss:
// sidebar
$menuText:var(--menuText,#464646);$menuActiveText:var(--menuActiveText,$--color-theme);
$subMenuActiveText:var(--subMenuActiveText,#464646);$menuBg:var(--menuBg,#ffffff);//侧边栏菜单主题色$menuTopBg:transparent;//顶栏菜单主题色
$menuHover:var(--menu,#F7FCFF);
$subMenuBg:var(--menu,#F7FCFF);
$subMenuHover:var(--menu,#F7FCFF);$sideBarWidth: 260px;
:export {menuText: $menuText;menuActiveText: $menuActiveText;subMenuActiveText: $subMenuActiveText;menuBg: $menuBg;menuTopBg: $menuTopBg;menuHover: $menuHover;subMenuBg: $subMenuBg;subMenuHover: $subMenuHover;sideBarWidth: $sideBarWidth;
}
展示结果: