首页 > 解决方案 > 在 Vue.js 中使用 Prop 更改背景颜色和伪元素颜色

问题描述

vue 中有没有办法使用道具来改变背景颜色,然后也会改变伪元素颜色?我希望能够调用该组件,然后将一个 css 变量传递给道具,然后该道具将更新 CTA 和伪元素的背景颜色。不确定这是否可能。

零件:

<template>
  <div class="callout" :style="{ backgroundColor: color }">
    <div class="callout__inner">
      <p>
        <slot name="callout-copy"></slot>
      </p>
    </div>
  </div>
</template>

<script>
export default {
  name: "CalloutWithAngle",
  props: {
    color: {
      type: String,
      required: true
    }
  },
  data() {
    return {};
  },
  methods: {}
};
</script>

<style scoped lang="scss">
.callout {
  position: relative;

  width: 100%;
  max-width: 885px;
  margin: 0 auto 45px;

  background-color: BACKGROUND COLOR FROM PROP

  @media (max-width: $smallMax) {
    margin-bottom: 20px;
  }

  &::before {
    position: absolute;
    z-index: -1;
    top: 100%;
    left: 0;

    display: block;

    width: 0;
    height: 0;

    content: "";
    transform: rotate(10deg);

    border-right: 100px solid transparent;
    border-bottom: 25px solid darken(BACKGROUND COLOR FROM PROP, 10%);
    border-left: 140px solid transparent;

    @media (max-width: $smallMax) {
      display: none;
    }
  }
}
.callout__inner {
  padding: 30px 40px;
  p {
    text-align: center;

    color: $white;

    font-weight: $robotoBold;

    @include fluid-type(font-size, $mobileMin, $mobileMax, 20px, 20px);
  }
}
</style>

组件调用:

  <CalloutWithAngle color="$pink"> <-- use variable here from css 
            <template slot="callout-copy">
             "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmo tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud, sunt in culpa qui officia deserunt mollit anim id est laborum."
            </template>
          </CalloutWithAngle>

标签: javascriptcssvue.jsnuxt.js

解决方案


根据道具更改背景颜色的最简单方法是将类绑定到您想要的元素,例如

<div class="base-class" v-bind:class="{ 'conditional-class': isActive }"></div>

conditional-class你的班级在哪里,isActive是道具名称。这将始终将类应用于元素何时isActive为真。

如果需要,您还可以通过创建这样的计算属性来绑定 CSS 类(不是 SCSS)

// data or props
color: '#fff'


//computed
bgColor() {
    return {
        '--bg-color': this.color
    };
},

然后将其绑定到元素:

<div :style="bgColor"></div>

最后,在您的样式中使用该变量

var(--bg-color);


推荐阅读