在vue中获取动态类的“活动”类名称

时间:2019-03-18 08:10:34

标签: javascript html5 class vue.js

我在Vue中有一张卡片的代码:

<div  id="card" class="card" :class="{'border-danger': alertaCPU }" style="max-width: 18rem;">

我使用此模板创建6个元素,并且在值超过限制的情况下边框变为红色。这是该函数的代码:

  alertaCPU: function() {
        if (this.valor > this.limite ) {
          this.audio.play();
          console.log("Playingg");

          return true;
        }
        return false;

      }

我尝试获取不同元素的类的名称:

document.getElementById("card").className

始终返回类的所有名称,而没有动态条件。

 card border-danger

是否可以获得当前使用的className?

1 个答案:

答案 0 :(得分:0)

对于此代码:class="{'border-danger': alertaCPU }",类条件始终返回 true alertaCPU始终是真实值,因为它是一个函数。

Vue.js类语法期望类对象具有以下类型:

{ 'class-name': truthyValue }

在这里,您只是传递一个函数名称,该名称始终为真实值。您必须像下面这样隐藏该功能才能获取

computed: {
    alertaCPU: function() {
        if (this.valor > this.limite ) {
        this.audio.play();
        console.log("Playingg");

        return true;
        }
        return false;

    }
}

第二,您的类"card"静态绑定到DOM元素,并且将始终存在,而与动态添加的类无关。您可以在此处执行正则表达式或.classList而不是.className属性,例如:

document.getElementById("card").classList;

classList 基本上是应用于该元素的所有类的数组。进一步了解here