【问题标题】:Apply multiple conditional classes in Vue在 Vue 中应用多个条件类
【发布时间】:2020-04-24 21:10:13
【问题描述】:

我在 Vue 中这样使用样式绑定:

v-bind:style="{'width': + width + 'px', 'left': + x + 'px', 'top': y + 'px'}"

当我需要绑定多个条件类时,我使用了下面的语法,但它不起作用!

v-bind:class="{(position)?position:'', (direction)?direction:''}"

还有其他方法可以应用多个类吗?单类(不带 {})有效。

这是小提琴:

https://jsfiddle.net/kunjsharma/o0kL7myt/

【问题讨论】:

  • 试试这个::class="{ position, direction }",或v-bind:class="[(position)?position:'', (direction)?direction:'']" [] 而不是{}
  • 当我在谷歌上搜索“vue 类绑定”时,我从官方文档中得到了this page 作为最高结果,这很容易回答你的问题。

标签: vue.js


【解决方案1】:

模板中的类绑定表达式是无效的 JavaScript 语法。

你的意思是像这样绑定一个数组吗:

:class="[position, direction]"

因此,如果 position'right' 并且 direction'rtl' 则该元素将应用 rightrtl 类。

绑定一个对象通常用于当你有静态类名,你想根据某些条件有条件地应用它。查看您的代码,这似乎不是您想要做的。

例如,如果您想根据某些条件有条件地应用静态类pressedactive,您可以这样做:

:class="{ pressed: pressedElement === el, active: !hidden }"

如果pressedElement === el 为真,那么该元素将获得应用到它的pressed 类,同样适用于active(我只是编造了一些任意表达式)。

【讨论】:

    【解决方案2】:

    类定义的基于对象的语法是:

    {
        className: isEnabled,
        anotherName: isOtherEnabled,
    }
    

    其中键 (className) 是类的名称,值 (isEnabled) 是它是否启用。

    所以在您的情况下,您可能需要{ position: position, direction: direction }。您甚至可以让 javascript 为您推断键名{ position, direction }

    如果您想将类名设置为位置和方向属性的值,那么您应该改用数组语法:[position, direction]。您也可以使用如下的类语法来实现这一点:{ [position]: true, [direction]: true }

    【讨论】:

    • 谢谢@James。将 {} 更改为 [] 会有所不同。
    【解决方案3】:

    您可以使用两种语法:

    • 对象::class="{ position, direction }"
    • 数组::class="[position ? 'position' : '', direction ? 'direction' : '']"

    您也可以将:class 设为字符串,但是当您想对多个类使用条件时,这会很麻烦。你也可以computed property:

    computed: {
      myClass: function() {
        return [position ? 'position' : '', direction ? 'direction' : ''].filter(c => !!c).join('');
      }
    }
    

    更多示例请参见Conditional Classes in Vue

    【讨论】:

    • 感谢您的回答,非常感谢。
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    相关资源
    最近更新 更多