Search code examples
javascriptcssvue.jsvuex

How to create Dynamic, not predefined, CSS styles in Vue (like we can in Angular)


In Angular we can dynamically set css properties, like this:

<style ng-if="color">
.theme-color { color: {{color}}; }
.theme-background-color { background-color: {{color}}; }
.theme-border-color { border-color: {{color}}; }
</style>

In Vue, we can modify :class=... but that limits us to predefined class options, and :style... that doesn't allow us to use class names.

Is there a way to achieve dynamic CSS as above? Or do we have to code the styles so that they include all color properties?

Thanks


Solution

  • Assuming this has some sort of user colour picking intervention; I would store the user's chosen colour in the state, so it's globally accessible.

    Then within your component, you could do the following...

    <app :style="themeStyles"></app>
    
    export default {
      computed: {
        themeStyles () {
          return {
            color: store.state.themeColor,
            backgroundColor: store.state.themeColor,
            borderColor: store.state.themeColor
          }
        }
      }
    }
    

    (Pseudocode so to provide example quickly)

    Obviously, use it on whatever component you need - but it should do the trick, so long as you have a way of storing user's input for the themeColor itself & store it in the state.

    Edit: additional option

    JSS