Vue3 中组件传递 + css 变量的组合

文章目录


需求

开发一个箭头组件,根据父组件传递的 props 来修改 css 的颜色

效果如下图所示


代码逻辑


代码

父组件:

html 复制代码
<Arrow color="red" />

子组件:

html 复制代码
<template>
  <div 
    class="arrow" 
    :style="{ 
      '--arrow-color': color, 
      '--arrow-width': `${width}px`,
      '--arrow-rotation': `${rotation}deg`
    }">
  </div>
</template>

<script lang='ts' setup>
import { defineProps } from 'vue';

const props = defineProps({
  color: {
    type: String,
    default: 'black'
  },
  width: {
    type: Number,
    default: 30
  },
  rotation: {
    type: Number,
    default: 0  // 旋转角度,默认不旋转
  }
});
</script>

<style scoped>
.arrow {
  display: inline-block;
  position: relative;
  margin: 10px;
  width: var(--arrow-width);
  transform: rotate(var(--arrow-rotation));  /* 添加旋转样式 */
}

.arrow::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: var(--arrow-width);
  border-top: 2px dotted var(--arrow-color);
  transform: translateY(-50%);
}

.arrow::after {
  content: '';
  position: absolute;
  top: 50%;
  left: calc(var(--arrow-width) - 8px);
  width: 0;
  height: 0;
  border-left: 10px solid var(--arrow-color);
  border-top: 7px solid transparent;
  border-bottom: 7px solid transparent;
  transform: translateY(-50%);
}
</style>

参考

1. 使用 CSS 自定义属性(变量) https://developer.mozilla.org/zh-CN/docs/Web/CSS/Using_CSS_custom_properties

相关推荐
掘金者阿豪11 分钟前
从Oracle迁到金仓,第一个月踩的最大的坑就是它
前端·后端
贾伟康19 分钟前
【安心陪诊 Agent v1.1】首页可信设计实战:HTML/CSS 状态卡与急症分流
css·html·harmonyos·ai agent·首页设计
AZaLEan__26 分钟前
CSS文档流相关:BFC
前端·css
小林ixn40 分钟前
Vue3接入DeepSeek流式输出,把“二进制碎片”和“局部热更新”扒个精光
前端·vue.js·人工智能
2501_9127840844 分钟前
Taocarts 前端国际化实战:多语言与多币种怎么落地不翻车
前端·多语言·taocarts
悟空瞎说1 小时前
AI 流式对话页面滚动抖动深度优化实战
前端
秋天的一阵风1 小时前
🔥 ECMAScript 2026 来了!使用这些新特性,JS 代码直接少一半
前端·javascript·ecmascript 6
小堂子这厢有礼了1 小时前
Chet.Admin 权限模型:菜单级 + 按钮级 + 行级三层防护
前端·后端·信息可视化·前端框架·.net
Cobyte1 小时前
编译解析器的基础——状态模式与状态机的原理
前端·javascript·vue.js
IT_陈寒2 小时前
Vue的这个响应式陷阱,让我加班到凌晨三点
前端·人工智能·后端