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

相关推荐
lecepin1 小时前
AI Coding 资讯 2025-09-17
前端·javascript·面试
IT_陈寒1 小时前
React 18实战:7个被低估的Hooks技巧让你的开发效率提升50%
前端·人工智能·后端
树上有只程序猿1 小时前
终于有人把数据库讲明白了
前端
猩兵哥哥2 小时前
前端面向对象设计原则运用 - 策略模式
前端·javascript·vue.js
司宸2 小时前
Prompt设计实战指南:三大模板与进阶技巧
前端
RoyLin2 小时前
TypeScript设计模式:抽象工厂模式
前端·后端·typescript
华仔啊2 小时前
Vue3+CSS 实现的 3D 卡片动画,让你的网页瞬间高大上
前端·css
江城开朗的豌豆2 小时前
解密React虚拟DOM:我的高效渲染秘诀 🚀
前端·javascript·react.js
vivo互联网技术2 小时前
拥抱新一代 Web 3D 引擎,Three.js 项目快速升级 Galacean 指南
前端·three.js