vue 项目配置全局主题色

利用 css 变量实现
这是最近刚学到的一种便捷操作,简直不要太方便
创建 vue 组件,将定义 css 变量的步骤放在一个单独的组件中,在 app.vue 页面去引用,进而应用全局。

  1. 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.然后你在页面中就可以直接使用
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值