【问题标题】:Use CSS variable in Vue component (scoped)在 Vue 组件中使用 CSS 变量(作用域)
【发布时间】: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


    【解决方案1】:

    您必须在此处使用 this.$refs 而不是 document.querySelector('.card')document.querySelector('.card') 正在获取页面上的第一个元素。使用 refs 您可以在卡片项目中选择对 DOM 元素的引用。请在模板中将ref 属性添加到您的div,并使用this.$refsdocument.querySelector('.card') 替换为您的div。

    参考:https://v3.vuejs.org/guide/component-template-refs.html

    【讨论】:

      【解决方案2】:

      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 }">
      

      【讨论】:

        猜你喜欢
        • 2019-04-13
        • 2017-04-02
        • 2021-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        相关资源
        最近更新 更多