vite+vue+ts+element-plus从零开发管理后台框架(18)-主颜色优化

问题

编辑src/views/Home.vue,添加一个主颜色的按钮。


正常

vite+vue+ts+element-plus从零开发管理后台框架(18)-主颜色优化_第1张图片

鼠标滑过

vite+vue+ts+element-plus从零开发管理后台框架(18)-主颜色优化_第2张图片

发现鼠标滑过后颜色出问题了,这是因为按钮样式使用了主颜色相关的变量,而主颜色相关的变量不止el-color-primary这个css变量。

按钮样式

vite+vue+ts+element-plus从零开发管理后台框架(18)-主颜色优化_第3张图片

主颜色变量

vite+vue+ts+element-plus从零开发管理后台框架(18)-主颜色优化_第4张图片

所以我们要把这些主颜色相关的变量都动态设置

解决

编辑src/store/color.ts,添加如下辅助方法。

import { defineStore } from 'pinia'


const color2rgb = (color: string) => {
    return color.startsWith('#') ? hex2rgb(color) : rgb2rgb(color)
}

// rgb(255, 0, 0) | rgba(255, 0, 0) => [255, 0, 0]
const rgb2rgb = (color: string) => {
    const colors = color.split('(')[1].split(')')[0].split(',')
    return colors.slice(0, 3).map(item => parseInt(item.trim()))
}

// #FF0000 => [255, 0, 0]
const hex2rgb = (color: string) => {
    color = color.replace('#', '')
    const matchs = color.match(/../g)

    const rgbs: number[] = []
    for (let i = 0; i < matchs!.length; i++) {
        rgbs[i] = parseInt(matchs![i], 16)
    }

    return rgbs
}

const rgb2hex = (r: number, g: number, b: number) => {
    const hexs = [r.toString(16), g.toString(16), b.toString(16)]

    for (let i = 0; i < hexs.length; i++) {
        if (hexs[i].length === 1) {
            hexs[i] = '0' + hexs[i]
        }
    }

    return '#' + hexs.join('')
}

// 颜色变亮
const lighten = (color: string, level: number) => {
    const rgbs = color2rgb(color)

    for (let i = 0; i < rgbs.length; i++) {
        rgbs[i] = Math.floor((255 - rgbs[i]) * level + rgbs[i])
    }

    return rgb2hex(rgbs[0], rgbs[1], rgbs[2])
}

// 颜色变暗
const darken = (color: string, level: number) => {
    const rgbs = color2rgb(color)

    for (let i = 0; i < rgbs.length; i++) {
        rgbs[i] = Math.floor(rgbs[i] * (1 - level))
    }

    return rgb2hex(rgbs[0], rgbs[1], rgbs[2])
}

修改primaryChange,添加如下动态设置css变量代码。

el.style.setProperty('--el-color-primary', val)

const lights = [3, 5, 7, 8, 9]
for (const light of lights) {
    el.style.setProperty(`--el-color-primary-light-${light}`, lighten(val, light / 10))
}

el.style.setProperty('--el-color-primary-dark-2', darken(val, 0.2))

const rgbs = color2rgb(val)
el.style.setProperty('--el-color-primary-rgb', `${rgbs[0]},${rgbs[1]},${rgbs[2]}`)

刷新浏览器,现在发现主颜色及相关的css变量全部设置成功了

vite+vue+ts+element-plus从零开发管理后台框架(18)-主颜色优化_第5张图片

你可能感兴趣的:(vue.js)