2

I have a master component named App.vue and in that file I am calling an ajax request to the server which returns JSON of colors.

My ajax call is located inside of the vue life cycle hook named created. When the ajax is done, it will populate the local data base on the result.

In the same file, I have style written in SCSS.

<style lang="scss">
$primary: #ff2000;
$secondary: #000111;
</style>

Is it possible to share to this SCSS file block those JSON of colors from the state of the components? Please imagine the below image attached.

enter image description here

** CORRECTIONS **

  1. this.colors = colors.data

  2. .color-secondary { background: $secondary; }

The colors are dynamic that is why it is coming from a database.

Thanks in advance.

3 Answers 3

5

I think I nailed it!! But I'm not quite sure if it is recommended or not. I don't even know yet the up and down side of doing this tweak. But it did work! :)

created() {
  // assume that this colors are coming from an async ajax call
  let colors = {
    primary: 'red',
    secondary: 'blue'
  }

  this.setThemeColors(colors);
},
methods: {
  setThemeColors(colors) {
    let style = document.documentElement.style;

    for (let key of Object.keys(colors)) {
      style.setProperty("--theme-color-" + key, colors[key]);
    }
  }
}

It's all set up from the root of your stylesheet. Check below to use it,

<style lang="scss">
$color-primary: var(--theme-color-primary);
$color-secondary: var(--theme-color-secondary);

.color-primary {
  color: var(--theme-color-primary)
}
.color-secondary {
  color: var(--theme-color-secondary)
}
</style>

But another problem encountered, css variables is not working in IE11 and below!

Sign up to request clarification or add additional context in comments.

Comments

1

It is not possible to update the values of SCSS variables dynamically like you want to. Web browsers do not understand SCSS, only CSS. SCSS is compiled into CSS ahead of time; the variables get compiled away.

Somewhat recently, CSS variables have become a thing, so maybe that could be something that you can consider looking into.

Other than that, you don't generally make dynamic updates to stylesheets. Perhaps some kind of CSS-in-JS solution might be what you're looking for.

Comments

0

The key feature of SCSS is that it compiles readable / less bloated CSS into normal CSS. Adjusting the styles on-the-fly inside a single file component is not possible.

See this question for possible workarounds: https://stackoverflow.com/a/48201646/6803592

If you're looking for a solution, you could possibly get the colors before your vue app loads.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.