Vue - 是否可以动态设置 html 元素的样式?

STh*_*STh 5 javascript css vue.js vue-component vuejs2

简短版本:data()我的应用程序中,我定义了某些颜色。我希望html根据switch声明将元素的背景设置为这些颜色之一。

长版本: 在 中data(),我有以下代码:

data() {
    return {
      item: {},
      color1: '',
      color2: '',
    };
  },
Run Code Online (Sandbox Code Playgroud)

在我的created()函数中,我从后端获取该项目。此外,我编写了以下代码来评估 - 部分的颜色html

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 = '#';
}
Run Code Online (Sandbox Code Playgroud)

在我的style部分中,我想设置整个应用程序(html-tag)的背景样式,样式如下:

data() {
    return {
      item: {},
      color1: '',
      color2: '',
    };
  },
Run Code Online (Sandbox Code Playgroud)

这可以用 Vue 实现吗?

Bou*_*him 5

不可能将脚本内的数据绑定到样式标签或任何样式表文件中的 CSS 规则,处理此问题的最佳方法是在主 CSS 样式文件中定义一些 CSS 变量并使用脚本更改它:

:root {
  --color1:#000;
 --color2:#fff;
}

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

Run Code Online (Sandbox Code Playgroud)

脚本 :

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)
Run Code Online (Sandbox Code Playgroud)