说明:本文是基于vue3.0+elementplus+less构建的vue项目
开发一些后台管理系统时,经常会使用到切换主题色,下文简单介绍一下基本做法
声明全局的css变量
在src下创建styles/index.less
// src/styles/index.less
@import 'var';
// src/styles/var.less
:root {
--colorA: #3963a2;
--colorB: #074575;
--colorC: #1398e6;
--colorD: deepskyblue;
--colorE: #6085b1;
}
/* 颜色规范定义 */
@blue: --colorA;
@blue2: --colorB;
@blue3: --colorC;
@text_color: rgba(255, 255, 255, 0.6);
@text_color_active: #fff;
在main.ts中引入index.less
// main.ts
import { createApp } from 'vue'
import '@/styles/index.less' // 全局引入css
const app = createApp(App)
app.mount('#app')
2.在组件中使用
<div class="h-[40] w-[100vw] text-rose-50 bg-theme">主题颜色</div>
<style scoped lang="less">
.bg-theme {
background: var(@blue);
}
</sytle>
页面效果:
3.修改全局主题色
<template>
<div class="bg-white h-[100vh] m-28">
<el-button @click="changeTheme('red')">切换主题红色</el-button>
<el-button @click="changeTheme('blue')">切换主题蓝色</el-button>
<el-button @click="changeTheme('yellow')">切换主题橙色</el-button>
<el-button type="primary">Primary</el-button>
<el-button type="success">Success</el-button>
</div>
</template>
<script setup lang="ts">
const changeTheme = color => {
document.documentElement.style.setProperty('--colorA', color)
document.documentElement.style.setProperty('--colorB', color)
}
</script>
<style scoped lang="less"></style>
从上图可以看出,我们不但可以修改头部的主题背景色,也可以修改el-button组件的颜色,一般情况下当我们修改主题色时,页面的按钮和菜单一般也要跟着变,这时候我们需要再App.vue中定义组件的这些样式
//App.vue
<style lang='less' scoped>
/deep/ .el-button--primary {
background-color: var(@blue) !important;
border-color: var(@blue) !important;
}
/deep/ .el-button--success {
background-color: var(@blue2) !important;
border-color: var(@blue2) !important;
}
</style>
同理,要想修改elementplus的其他组件样式,也可以采用上面的方式