直接放代码,很简单
需要安装一个颜色转换的库 TinyColor
TinyColor-npm
代码
app.vue
<script setup lang="ts">
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import { computed, onMounted, watch } from 'vue';
import { ElNotification } from 'element-plus';
import { useUserStore } from '@/store/index';
import tinycolor from 'tinycolor2';
const userStore = useUserStore();
const color = computed(() => userStore.baseForm.color);
// 监听浏览器版本
// @ts-ignore
import getBsInfo from 'browser-tag';
const bsInfo = getBsInfo(); // { bs_name: "chrome浏览器", bs_tag: "chrome", bs_version: "108.0.0.0" },
console.log(bsInfo);
if (bsInfo.bs_tag === 'firefox' && bsInfo.bs_version.split(',')[0] < 100) {
ElNotification({
title: '警告',
message: '当前浏览器版本过低,部分功能不可用,请更新火狐浏览器版本(不低于100.x版本)',
type: 'warning',
duration: 0,
});
}
onMounted(() => {
// 初始化主题色
setColor(color.value);
});
// 更新主题色
watch(
() => color.value,
(newValue, oldValue) => {
setColor(newValue);
},
);
const setColor = (color: string) => {
// document.documentElement 是全局变量时
const el = document.documentElement;
// 主题色系
// --el-color-primary: #f0905a;
// --el-color-primary-light-3: #f2a67a;
// --el-color-primary-light-5: #f4b88c;
// --el-color-primary-light-7: #f6c99e;
// --el-color-primary-light-8: #f7d3ab;
// --el-color-primary-light-9: #f8ddba;
// --el-color-primary-dark-2: #e88e4e;
// 主题色系算法
const getColorMap = (color: string) => {
const colorMap = {
'--el-color-primary': color,
'--el-color-primary-light-3': light(color, 3),
'--el-color-primary-light-5': light(color, 5),
'--el-color-primary-light-7': light(color, 7),
'--el-color-primary-light-8': light(color, 8),
'--el-color-primary-light-9': light(color, 9),
'--el-color-primary-dark-2': dark(color, 2),
};
function light(color: string, level: number) {
return tinycolor(color)
.lighten(level * 5)
.toString();
}
function dark(color: string, level: number) {
return tinycolor(color)
.darken(level * 5)
.toString();
}
return colorMap;
};
// 设置 css 变量
const colorMap: any = getColorMap(color);
for (const key in colorMap) {
el.style.setProperty(key, colorMap[key]);
}
};
</script>
<template>
<el-config-provider :locale="zhCn">
<router-view />
</el-config-provider>
</template>
<style scoped></style>