[Vuejs]-Vue3 setting css styles from vuex store

0👍

UPDATE 6 April 2022

Apparently I was wrong and in Vue 3 it is possible to use v-bind inside CSS as shown in the documentation. So it should be possible to use Vuex getter or local computed property.


You can not access JavaScript variables from CSS. You should either set inline style to your HTML tag(s) or define the color as CSS variable and then access it from other CSS rules.

<template>
  <div :style="{backgroundColor: brandingColor}">test</div>
</template>

<script>
export default
{
  computed:
  {
    brandingColor()
    {
      return this.$store.state.branding.color;
    }
  }
}
</script>

OR

// main.js

new Vue({
  created()
  {
    const style = document.documentElement.style;
    const theme = this.$store.state.branding;
    for (const key in theme)
    {
      style.setProperty('--branding-' + key, theme[key]);
    }
  }
});

MyComponent.vue:

<template>
  <div class="page">text</div>
</template>

<style>
.page
{
  background-color: var(--branding-color);
}
</style>

Leave a comment