目录
思路
安装css-color-function【接收一个颜色值,生成不同的透明度】
获取后台配置的主题色或者使用ColorPicker修改主题色
最终结果如下
思路
本篇文章的主体思路是从element Plus官网引申而来。结合了我以前用vue2+element-ui配置主题色生成透明度(light-1至linght-9)的方法。
安装css-color-function【接收一个颜色值,生成不同的透明度】
pnpm i css-color-function
utils/color.ts
import color from 'css-color-function'
const formula = {"dark-2": "color(primary shade(10%))","light-1": "color(primary tint(10%))","light-2": "color(primary tint(20%))","light-3": "color(primary tint(30%))","light-4": "color(primary tint(40%))","light-5": "color(primary tint(50%))","light-6": "color(primary tint(60%))","light-7": "color(primary tint(70%))","light-8": "color(primary tint(80%))","light-9": "color(primary tint(90%))"
}
const generateColors = primary => {const colors = {}Object.keys(formula).forEach(key => {const value = formula[key].replace(/primary/g, primary)colors[key] = color.convert(value)})return colors}export default generateColors
tsconfig.json需要加入以下两个配置(因为css-color-function不是ts写的)
"allowJs": true,"checkJs": false
获取后台配置的主题色或者使用ColorPicker修改主题色
XXXX.vue
<script lang='ts' setup>
//更换主题色
import generateColors from '@/utils/color'
let themeColor = ref('#FF8040')//假装这个是从后台获取的主题色
function toggleTheme(){let colorMap:any = generateColors(themeColor.value)const el = document.documentElementel.style.setProperty('--el-color-primary',themeColor.value)//生成不同1-9的透明度Object.keys(colorMap).forEach(key => {el.style.setProperty(`--el-color-primary-${key}`, colorMap[key])})}
</script>
<template><el-color-picker v-model="themeColor" @change="toggleTheme" />
</template>