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

标签 javascript css vue.js vuejs2 vue-component

简短版:在我的应用程序的 data() 中,我定义了某些颜色。基于 switch 语句,我希望 html 元素的背景为其中一种颜色。

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

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

在我的 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 = '#';
}

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

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

这在 Vue 中可行吗?

最佳答案

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

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

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

脚本:

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)

关于javascript - Vue - 是否可以动态设置 html 元素的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61228806/

相关文章:

javascript - 获取数组的替代值

javascript - Vue.js - 通过计算属性从数组中获取唯一值

vue.js - Cypress Vue 组件测试从已挂载发出的事件

vue.js - VueJS 2 $emit 和 $on

javascript - 对另一个值使用react的验证指令在 1.0.x 中有效,但在 1.2.x 中无效

javascript - ES5 "strict"和 arguments.callee

javascript - 将 jQuery UI 时间 slider 间隔更改为小时,并添加刻度

java - 找到一个独特的定位器 Selenium WebDriver

javascript - 如何优化大型 HTML 文件

javascript - 可以正确处理溢出的可滚动选项卡