绑定类的 Vue 条件 [英] Vue conditionals for binding classes

查看:27
本文介绍了绑定类的 Vue 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何基于 vue 模型有条件地将类绑定到表行.

I'm trying to figure out how to bind classes to a table row conditionally based on a vue model.

我的刀片里有:

.low-priority{
    background-color: purple;
}
.high-priority{
    background-color: orange;
}
.important-priority{
    background-color: yellow;
}
.critical-priority{
    background-color: red;
}

在我的 vue 模板中,我返回一个 dateEvents 对象,该对象具有一个名为 priority 的值,它可以是 "High", 低"重要"严重".

and in my vue template I return a dateEvents object which has a value called priority which can be "High", "Low", "Important" or "Critical".

我想通过这些优先级来设置这个表行的类:

I want to set the class of this table row by those priorities:

<tr v-bind:class="dateEvent">

如果返回为真或假,我已经看过绑定类的文档,但是我如何使用条件适当地执行此操作,即 if dateEvent.priority === 'Low' then class is .low- 优先级'

I've seen the docs for binding a class if a return is true or false, but how do I do this appropriately with conditionals, i.e. if dateEvent.priority === 'Low' then class is .low-priority'

推荐答案

不确定在这种情况下是否需要条件:

Not sure you need a conditional in this case:

<tr :class="`${dateEvent.priority.toLowerCase()}-priority`">

或者如果您不喜欢反引号:

Or if you don't like backticks:

<tr :class="dateEvent.priority.toLowerCase() + '-priority'">

更通用的解决方案是使用计算属性.不过在这种情况下会有点重复.

A more general solution would be to use a computed property. In the circumstances that would be a bit repetitive though.

<tr :class="rowClass">

computed: {
  rowClass () {
    const priority = this.dateEvent.priority

    return {
      'low-priority': priority === 'Low',
      'high-priority': priority === 'High',
      'important-priority': priority === 'Important',
      'critical-priority': priority === 'Critical'
    }
  }
}

如果 dateEvents 不能通过 this 获得,因为它是一个循环参数(即来自 v-for),那么你会做 rowClass 一个方法,并从模板中传入 dateEvents.

If dateEvents isn't available via this because it's a loop parameter (i.e. from v-for) then you'd make rowClass a method instead and pass in dateEvents from the template.

该主题的其他变体可用:https://vuejs.org/v2/guide/class-and-style.html

Other variations on that theme are available: https://vuejs.org/v2/guide/class-and-style.html

这篇关于绑定类的 Vue 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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