【发布时间】:2021-11-27 20:31:28
【问题描述】:
目前我需要 3 个卡片组件,全部具有三种不同的颜色。颜色应用于:before 伪元素(以及多个其他区域),因此我认为最简单的解决方案是将其与 CSS 变量/属性一起应用。
目前,我在组件的mounted() 中实例化了一个新的 CSS 属性/变量,这适用于 1 张卡,但会中断多张卡。当我有多个组件时,只有第一个获得颜色,第二个甚至没有颜色。它似乎用第一个组件覆盖了以前的颜色,然后完全忽略了第二个(第二个的开发工具中没有显示颜色属性)。
我的问题是,这个问题的最佳解决方案是什么?有没有办法轻松添加不覆盖其他变量的作用域 CSS 变量?或者最好的做法是在 JavaScript 中添加所有这些样式?
Vue 组件
<template>
<div :class="'card ' + clss">
<div class="card-top">
<h3>{{ title }}</h3>
</div>
<div class="card-center">
<p>{{ message }}</p>
</div>
<div class="card-bottom">
<a href="" class="btn-p card-btn">Learn more</a>
</div>
</div>
</template>
<script>
export default {
name: "Card",
props: ['clss', 'color', 'title', 'message'],
data() {
return {
}
},
mounted() {
var style = document.querySelector('.card').style;
style.setProperty(`--color`, this.color);
},
}
</script>
<style lang="scss" scoped>
// Example, not all styles are shown
.card:before {
content: "";
position: absolute;
z-index: -1;
top: -16px;
right: -16px;
background: var(--color); // Example of where I need this color
}
</style>
包含所有组件的 Vue
<template>
<div class="grid grid-cols-12">
<!-- Green -->
<Card
title="Lorem1"
message="Lorem"
color="#00838d"
clss="col-span-4"
>
</Card>
<!-- Purple -->
<Card
title="Lorem2"
message="--bg-color"
color="#0066b2"
clss="col-span-4"
>
</Card>
</div>
</template>
【问题讨论】:
标签: javascript vue.js