Skip to content

1. How to use scss in vue project

bo-er edited this page Nov 25, 2020 · 4 revisions

Original Author: Marina Mosti

Original Webpage: Passing Variables to CSS on a Vue Component

The following codes are flawed. They aren't neat enough.

<template>
  <button :style="btnStyles">My button</button>
</template>

<script>
export default {
  name: 'SimpleButton',
  props: {
    bgColor: {
      type: String,
      default: "#0099CC"
    },
    height: {
      type: Number,
      default: 100
    }
  },
  computed: {
    btnStyles() {
      return {
        "background-color": this.bgColor,
        height: `${this.height}px`
      };
    }
  }
};
</script>

A better solution should be like this:

computed: {
    cssVars() {
      return {
        '--bg-color': this.bgColor,
        '--height': this.height + 'px'
      }
    }
  }

And in our button:

<button :style="cssVars">My button</button>

What :style="cssVars" does look like this:

look!

And finally we modify our css part:

<style scoped>
button {
  color: var(--text-color);
  background-color: var(--bg-color);
  height: var(--height);
}
</style>

Clone this wiki locally