Search code examples
javascriptcssvue.jsvuejs2vue-component

Vue - Is it possible to style the html-element dynamically?


Short version: In the data() of my app, I define certain colors. I want the html-element's background to one of these colors, based on a switch statement.

Long version: In the data(), I've the following code:

data() {
    return {
      item: {},
      color1: '',
      color2: '',
    };
  },

In my created() function, I get the item from my backend. Furthermore I have written the following code to evaluate the colors for the html-section:

switch (this.item.itemType) {
    case 'car': this.color1 = '#39ac39'; this.color2 = '#00ff00'; break;
    case 'bus': this.color1 = '#3333ff'; this.color2 = '#1a75ff'; break;
    case 'plane': this.color1 = '#ff66cc'; this.color2 = '#ffb3e6'; break;

    default: this.color1 = '#'; this.color2 = '#';
}

In my style section, I want to style the background of my whole app (html-tag), to be styled like this:

<style>
html {
  background-color: linear-gradient(to bottom, color1, color2);
}
</style>

Is this possible with Vue?


Solution

  • It's not possible to bind a data inside your script to CSS rules in the style tag or any stylesheet file, the best way to deal with this is to define some CSS variables in the main CSS style file and change it using a script :

    :root {
      --color1:#000;
     --color2:#fff;
    }
    
    html {
      background-color: linear-gradient(to bottom,var(--color1), var(--color2));
    }
    
    

    script :

    switch (this.item.itemType) {
        case 'car': this.color1 = '#39ac39'; this.color2 = '#00ff00'; break;
        case 'bus': this.color1 = '#3333ff'; this.color2 = '#1a75ff'; break;
        case 'plane': this.color1 = '#ff66cc'; this.color2 = '#ffb3e6'; break;
    
        default: this.color1 = '#'; this.color2 = '#';
    }
    
    document.documentElement.style.setProperty("--color1", this.color1)
    
    document.documentElement.style.setProperty("--color2", this.color2)