【问题标题】:Get the "active" class name of a dynamic class in vue获取vue中动态类的“活动”类名
【发布时间】:2019-03-18 08:10:34
【问题描述】:

我在 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?

【问题讨论】:

  • 请在 js fiddle 上重现问题并在此处发布链接

标签: javascript html class vue.js


【解决方案1】:

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

Vue.js 类语法要求类对象为以下类型:

{ 'class-name': truthyValue }

这里你只是传递一个函数名,它总是一个真实值。您必须将此函数转换为 getter,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    相关资源
    最近更新 更多