利用 css 变量实现
这是最近刚学到的一种便捷操作,简直不要太方便
创建 vue 组件,将定义 css 变量的步骤放在一个单独的组件中,在 app.vue 页面去引用,进而应用全局。
- vue 组件创建如下
<template>
<component is="style">{{ bindGlobalStyle }}</component>
</template>
<script setup lang="ts">
import { PlatExtendUtil } from './../../utils/PlatExtendUtil.ts'
import { computed } from 'vue'
const props = defineProps<{
globalStyle: object
}>()
const bindGlobalStyle = computed(() => {
let styleHtml = ':root {\n'
for (const key in props.globalStyle) {
const styleKey = key.indexOf('--') === 0 ? key : `--${key}`
const styleValue = props.globalStyle[key]
styleHtml += `${styleKey}: ${styleValue};\n`
if (key.indexOf('Color') > 0 && PlatExtendUtil.isHexColor(styleValue)) {
styleHtml += `${styleKey}Rgb: ${PlatExtendUtil.hexToRgb(styleValue)};\n`
}
}
styleHtml += '}'
return styleHtml
})
</script>
--------------isHexColor和hexToRgb方法-----------------
function isHexColor (colorStr: string): boolean {
// 使用test方法检查字符串是否匹配模式
return hexColorPattern.test(colorStr);
}
function hexToRgb (hexStr: string): string {
let sColor = hexStr.toLowerCase()
if (isHexColor(sColor)) {
if (sColor.length === 4) {
let sColorNew = '#'
for (let i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
}
sColor = sColorNew
}
// 处理六位的颜色值f
const sColorChange = []
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt(`0x${sColor.slice(i, i + 2)}`))
}
const rgbText = sColorChange.join(',')
return rgbText
} else {
return sColor
}
}
其中isHexColor方法是用来判断当前色值是否是#开头的 hex色值,
hexToRgb方法是将 hex 色值转为 rgb 类型,rgb 类型可调透明度
2.在 app.vue 中引用组件并传入色值变量
3.然后你在页面中就可以直接使用