Vue-是否可以动态设置html元素的样式? [英] Vue - Is it possible to style the html-element dynamically?

查看:40
本文介绍了Vue-是否可以动态设置html元素的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短版本:在我的应用程序的 data()中,我定义了某些颜色.我希望基于 switch 语句将 html -element的背景设置为这些颜色之一.

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.

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

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

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

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

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

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

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>

Vue是否可能?

推荐答案

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

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));
}

脚本:

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)

这篇关于Vue-是否可以动态设置html元素的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆