using sass variables in vue data

·

1 min read

If you have a .scss file that stores your project's colors, you can easily reference those values in Vue. I recently ran into this issue when using a third-party library that required styling information to be set in data(). Overriding the default styles in this library using ::v-deep was not an option because of the complexity of how this component renders. Luckily, importing sass variables to your javascript is really simple.

In your sass file, provide an :export object:

:export {
  Red: $red;
  Orange: $orange;
  Deepyellow: $deepyellow;
  Canary: $canary;
  Black: $black;
}

Then, in your Vue component, you can import these styles:

import styles from '@src/styles.scss';

You can then access these styles throughout the Vue component. In my case, I needed to set colors in data() like this:

data() {
   return {
      eventDataTransform: eventData => {
          return {
              title: eventData.title,
              start: eventData.start,
              end: eventData.end,
              borderColor: styles.Black,
              textColor: styles.Black,
              color: styles.Canary,
          }
     }
},

If you have a ton of variables in your styles.css file, you might not want to import all of them. You can import just the ones you need like this:

import { Black, Red } from '@src/styles.scss';