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

相关推荐
namekong81 天前
清理谷歌浏览器垃圾文件 Chrome “User Data”
前端·chrome
开发者小天1 天前
调整为 dart-sass 支持的语法,将深度选择器/deep/调整为::v-deep
开发语言·前端·javascript·vue.js·uni-app·sass·1024程序员节
李少兄1 天前
HTML 表单控件
前端·microsoft·html
学习笔记1011 天前
第十五章认识Ajax(六)
前端·javascript·ajax
消失的旧时光-19431 天前
Flutter 异步编程:Future 与 Stream 深度解析
android·前端·flutter
曹牧1 天前
C# 中的 DateTime.Now.ToString() 方法支持多种预定义的格式字符
前端·c#
勿在浮沙筑高台1 天前
海龟交易系统R
前端·人工智能·r语言
歪歪1001 天前
C#如何在数据可视化工具中进行数据筛选?
开发语言·前端·信息可视化·前端框架·c#·visual studio
Captaincc1 天前
AI 能帮你写代码,但把代码变成软件,还是得靠人
前端·后端·程序员
繁花与尘埃1 天前
CSS引入方式(本文为个人学习笔记,内容整理自哔哩哔哩UP主【非学者勿扰】的公开课程。 > 所有知识点归属原作者,仅作非商业用途分享)
css·笔记·学习