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

相关推荐
Software攻城狮2 分钟前
【uniapp和普通web 端开发的区别】
前端·uni-app·notepad++
IT_陈寒4 分钟前
Vue项目实战经验分享:动态组件在Keep-Alive下的缓存陷阱
前端·人工智能·后端
数智奔流17 分钟前
MiniMax的低价攻势,撞上“背题”疑云
前端·javascript·算法
2601_9540056218 分钟前
11 种触发 × 18 种行为:ricon 交互编排系统全解
前端·后端·物联网·数学建模·信息可视化·交互
某人辛木33 分钟前
Web前端框架应用(三)路由
前端·javascript·前端框架
风骏时光牛马37 分钟前
智能任务协作Agent
前端
itmigrate10 小时前
前端项目里,Object.is 并不是 === 的平替
前端
小大宇11 小时前
Vue知识点6-computed计算属性
前端·javascript·vue.js
程序员海军12 小时前
尤雨溪 : Vue 4 已经在规划中了!
前端·javascript·vue.js