目前我需要 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>
最佳答案
你必须在这里使用 this.$refs 而不是 document.querySelector('.card')
。
document.querySelector('.card')
是页面上的第一个元素。使用 refs 您可以在卡片项目中选择对 DOM 元素的引用。请将 ref
属性添加到模板中的 div
,并使用 this.$refs
.
关于javascript - 在 Vue 组件中使用 CSS 变量(作用域),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70138474/