【问题标题】:Vue - Is it possible to style the html-element dynamically?Vue - 是否可以动态设置 html 元素的样式?
【发布时间】:2020-07-28 10:15:18
【问题描述】:

短版:在我的应用程序的data() 中,我定义了某些颜色。我希望html-element 的背景为这些颜色之一,基于switch 声明。

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

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

在我的 created() 函数中,我从后端获取项目。此外,我编写了以下代码来评估 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),样式如下:

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

Vue 可以做到这一点吗?

【问题讨论】:

    标签: javascript css vue.js vuejs2 vue-component


    【解决方案1】:

    无法将脚本中的数据绑定到样式标签或任何样式表文件中的 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)
    

    【讨论】:

      【解决方案2】:

      即使您不能直接操作样式标签或在组件的模板中添加style 标签,您也可以使用技巧来添加动态生成的样式表。

      可以使用v-html生成动态样式

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

      取自计算属性。

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

      但这只会在组件在树视图中时存在,一旦删除,您的样式也会消失。

      Here's 一个工作示例。

      【讨论】:

      • 仅作记录,我认为@Boussadjra Brahim 解决方案更好:)
      猜你喜欢
      • 2021-11-25
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多