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

相关推荐
快起来别睡了几秒前
手写 Ajax 与 Promise:从底层原理到实际应用
前端
打不着的大喇叭1 小时前
uniapp的光标跟随和打字机效果
前端·javascript·uni-app
无我Code1 小时前
2025----前端个人年中总结
前端·年终总结·创业
程序猿阿伟1 小时前
《前端路由重构:解锁多语言交互的底层逻辑》
前端·重构
Sun_light1 小时前
6个你必须掌握的「React Hooks」实用技巧✨
前端·javascript·react.js
爱学习的茄子1 小时前
深度解析JavaScript中的call方法实现:从原理到手写实现的完整指南
前端·javascript·面试
莫空00001 小时前
Vue组件通信方式详解
前端·面试
呆呆的心1 小时前
揭秘 CSS 伪元素:不用加标签也能玩转出花的界面技巧 ✨
前端·css·html
susnm1 小时前
Dioxus 与数据库协作
前端·rust
优雅永不过时_v1 小时前
基于vite适用于 vue和 react 的Three.js低代码与Ai结合编辑器
前端·javascript