Vue2 项目中使用 CSS 变量并更改 ElementUI 主题

免责声明

我这里使用了 CSS 预处理器 Scss 语法,配合 ElementUI 更改主题不需要额外的配置,因为 ElementUI 就是使用 Scss 写的,不过不是 Scss 的话需要装额外的插件,参考 ElementUI 官网

在 Vue 文件中使用 CSS 变量

@/styles/variables.scss 文件中存放了所有自定义的 scss 变量,我这里使用的是 Webpack5 最新的版本,然后就出问题了,本地开发的时候没有毛病,打包到线上就识别不了这些变量了,我这里通过重命名解决的,就是把 variables.scss 这个文件名改成 variables.module.scss 就可以了,神奇吧

$themeColor: #004098;

// sidebar
$menuText: #000;
$menuActiveText: $themeColor;
$subMenuActiveText: $themeColor;

$menuBg: transparent;
$menuHover: #d6e4ff;

$subMenuBg: transparent;
$subMenuHover: #d6e4ff;

$sideBarWidth: 210px;

// the :export directive is the magic sauce for webpack
// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass
:export {
  menuText: $menuText;
  menuActiveText: $menuActiveText;
  subMenuActiveText: $subMenuActiveText;
  menuBg: $menuBg;
  menuHover: $menuHover;
  subMenuBg: $subMenuBg;
  subMenuHover: $subMenuHover;
  sideBarWidth: $sideBarWidth;
}

然后就是在 vue 文件中使用了,我这里封装了个侧边栏组件:

<template>
  <el-scrollbar wrap-class="scrollbar-wrapper">
    <el-menu
      :default-active="activeMenu"
      :collapse="false"
      :background-color="variables.menuBg"
      :text-color="variables.menuText"
      :unique-opened="false"
      :active-text-color="variables.menuActiveText"
      :collapse-transition="false"
      mode="vertical"
    >
      <sidebar-item
        v-for="route in routes"
        :key="route.path"
        :item="route"
        :base-path="route.path"
      />
    </el-menu>
  </el-scrollbar>
</template>

<script>
import SidebarItem from "./SidebarItem";
import variables from "@/styles/variables.module.scss";

export default {
  components: { SidebarItem },
  computed: {
    routes() {
      return this.$router.options.routes;
    },
    activeMenu() {
      const route = this.$route;
      const { meta, path } = route;
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu;
      }
      return path;
    },
    variables() {
      return variables;
    },
  },
};
</script>

反正就是先 import 一下,再到 computed 里面包装一下,然后就可以在 js 代码中用了

更改 ElementUI 主题

新建一个 @/styles/element-variables.scss 文件,写入:

@import "./variables.module.scss";

/* 改变主题色变量 */
$--color-primary: $themeColor;

$--color-danger: #ff4d4f;

/* 改变 icon 字体路径变量,必需 */
$--font-path: "~element-ui/lib/theme-chalk/fonts";

@import "~element-ui/packages/theme-chalk/src/index";

然后在入口 main.js 中引入:

import Vue from "vue";

import ElementUI from "element-ui";
import "./styles/element-variables.scss"; // 引入
Vue.use(ElementUI);

通过更改 $themeColor 这个变量就可以实现一键换装了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值