Konobeyev Konstantin
Konobeyev Konstantin

Reputation: 95

Dynamically create scss variable in vuejs

In my App.vue @mounted() I create an api request to get stuff for my Application. In a response-property "style" i get json with styles. Which lookes like this:

"style": {
          "general": {
            "font-family": "",
            "font-color": "",
            "title_font_color": "",
            "h1_font_color": "",
            "background_color": "",
            "sale_background_color": "",
            "radius": ""
          },
          "cta": {
            "cta_color": "",
            "btn_font_color": "",
            "radius": "",
            "bar_background": "",
            "bar_font_color": ""
          },
          "navigation": {
            "normal_color": "",
            "normal_background_color": "",
            "focus_color": "",
            "focus_background_color": ""
          },
          "floating_icons": {
            "main_color": "",
            "phone_color": "",
            "mail_color": "",
            "whatsapp_color": ""
          }
        },

I would like to generate scss variables like:

$general_font_family: font-family;
$general_font_color: font-color;

and so on. In main.js I import styles.sass where a variables.scss is included too.

Question: Where and how can I define all these variables with JS in App.vue and pass it to styles.sass? thanks in advance =)

Upvotes: 6

Views: 5242

Answers (1)

Harshal Patil
Harshal Patil

Reputation: 20970

You cannot generate SCSS variables in JavaScript (more specifically, at browser side). SCSS is a compiler from SCSS to CSS. Even if you are importing SCSS file in your main.js, it is working due to Webpack/Rollup bundler are invoking SCSS compiler at build-time.

What you can do alternately is to create CSS custom properties (very similar to SCSS variables). In your CSS or SCSS, declare custom properties block like:

:root {
  /* default value */
  --general-font-family: serif;
}

div {
  /* default value */
  --general-font-color: brown;
}

Then using the JavaScript or VUe component you can start setting these CSS custom properties:

mounted() {
    // Ensure that you have proper reference to HTMLElement
    element.style.setProperty('--general-font-family', 'sans-serif');
}

Upvotes: 7

Related Questions