目前我需要有 3 個卡片組件,它們都具有三種不同的顏色。顏色應用于:before偽元素(和多個其他區域),因此我認為最簡單的解決方案是將其與 CSS 變數/屬性一起應用。
目前,我在mounted()我的組件中實體化了一個新的 CSS 屬性/變數,這適用于 1 張卡,但會中斷多個。當我有多個組件時,只有第一個獲得顏色,第二個甚至沒有獲得顏色。它似乎用第一個組件覆寫了前一個顏色,然后完全忽略了第二個(第二個開發工具中沒有顯示顏色屬性)。
我的問題是,這個問題的最佳解決方案是什么?有沒有辦法輕松添加不覆寫其他變數的作用域 CSS 變數?或者最好的做法是在 JavaScript 中添加所有這些樣式?
組件
<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>
uj5u.com熱心網友回復:
你必須在這里使用 this.$refs 而不是document.querySelector('.card'). 該document.querySelector('.card')走的是頁面上的一個第一要素。使用 refs 您可以選擇對卡片專案內的 DOM 元素的參考。請將ref屬性添加到您div的模板中,并document.querySelector('.card')使用this.$refs.
參考:https : //v3.vuejs.org/guide/component-template-refs.html
uj5u.com熱心網友回復:
CSS 是級聯的,變數應該應用于元素的層次結構。在 Vue 組件中直接訪問 DOM 是一個不好的跡象。document.querySelector查詢所有元素,無論它們屬于哪個組件實體,也只訪問與當前組件實體無關的元素。
如果需要在組件中訪問 DOM 元素,這通常是通過 refs 完成的:
<div :class="'card ' clss" ref="card">
和
mounted() {
this.$refs.card.style.setProperty(`--color`, this.color);
},
CSS 變數(自定義屬性)主要用于為嵌套樣式提供值。如果在同一組件中指定了樣式,則不需要:
<div :class="'card ' clss" :style="{ background: color }">
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/367803.html
標籤:javascript Vue.js
上一篇:如何剪輯影像以洗掉其填充
