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

余生长醉 提交于 2020-08-08 05:54:12

问题


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?


回答1:


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)



回答2:


Even though you cannot directly manipulate style tags or add style tags in the component's template you can use a trick to add dynamically generated stylesheets.

You can use v-html to generate a dynamic style

<span v-html="style"></span>

taken from a computed property.

computed: {
    style() {
      return (
        "<style> html { background-image: linear-gradient(to bottom, " +
        this.color1 +
        ", " +
        this.color2 +
        "); }</style>"
      );
    }
  }

But this will only exist as long as the component is in the tree view, once removed your style will also go.

Here's a working example.



来源:https://stackoverflow.com/questions/61228806/vue-is-it-possible-to-style-the-html-element-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!