简体   繁体   English

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

[英]Get the “active” class name of a dynamic class in vue

I have this code for a card in vue: 我在Vue中有一张卡片的代码:

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

I create 6 elements with this template and the border becomes red in the cases that the value gets over a limit. 我使用此模板创建6个元素,并且在值超过限制的情况下边框变为红色。 This is the code for the function: 这是该函数的代码:

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

          return true;
        }
        return false;

      }

I try to get the name of the class of the different elements : 我尝试获取不同元素的类的名称:

document.getElementById("card").className

And all the time it returns all the name of the class without the dynamic condition. 而且,它总是在没有动态条件的情况下返回类的所有名称。

 card border-danger

Is possible to get the className that is been used at this moment? 是否可以获取当前使用的className?

For this code :class="{'border-danger': alertaCPU }" , class condition always returns true ; 对于此代码:class="{'border-danger': alertaCPU }" ,类条件始终返回true alertaCPU is always truthy value since it is a function. alertaCPU是一个函数,因此始终是真实值

Vue.js class syntax expects a class object to be of the following type: Vue.js类语法期望类对象具有以下类型:

{ 'class-name': truthyValue }

Here you are just passing a function name which is always a truthy value . 在这里,您只是传递一个始终是真实值的函数名。 You must covert this function to getter like following: 您必须隐蔽此功能才能像下面这样进行吸气

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

        return true;
        }
        return false;

    }
}

Second, your class "card" is statically bound to your DOM element and will always exists irrespective of the dynamically added class. 其次,您的类"card"静态绑定到您的DOM元素,并且无论动态添加的类如何,该类都将始终存在。 What you can do here is to Regular Expression or .classList instead of .className property like: 您可以在此处执行正则表达式或.classList而不是.className属性,例如:

document.getElementById("card").classList;

classList is basically an array of all the classes applied to that element. classList基本上是应用于该元素的所有类的数组。 Read more about it here . 在此处了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM