【问题标题】:Uing Vue.JS v-bind:class with conditional statement of dynamically created array使用 Vue.JS v-bind:class 和动态创建数组的条件语句
【发布时间】:2019-07-05 12:00:30
【问题描述】:

我有一个表,它是在我的 Vue 应用程序中创建一个名为 shelves 的数组时创建的。

<table>
  <tr v-for="(shelf, index) in shelves">
    <td>
      <input type="number" v-model="shelf.maxWeight">
     </td>
  </tr>
<table>

我想根据输入框中值的长度将一个名为error 的html 类绑定到创建的每个输入框。我在想它会是这样的:

    <td>
      <input type="number" v-model="shelf.maxWeight" v-bind:class="error: shelf.maxWeight.length < 1">
    </td>

但是每当我尝试这样做时,页面都不会加载,并且我在控制台中收到错误消息:

invalid expression: Unexpected token : in
error: shelf.maxWeight.length < 1
Raw expression: v-bind:class="error: shelf.maxWeight.length < 1"

我一直在寻找 here,但似乎找不到任何关于如何具体执行此操作的参考。

如何根据表引用的数组中值的长度更改输入字段中的类?

【问题讨论】:

    标签: javascript arrays vue.js conditional two-way-binding


    【解决方案1】:

    v-bind:class 将对象作为参数,如您提供的链接中所述。

    你的代码应该是这样的

        <td>
          <input type="number" v-model="shelf.maxWeight" v-bind:class="{error: shelf.maxWeight.length < 1}">
        </td>
    

    注意类对象周围的花括号

    【讨论】:

      【解决方案2】:

      你需要绑定一个对象到class:

      v-bind:class="{ error: shelf.maxWeight.length < 1 }"
                    ^                                   ^
      

      【讨论】:

        猜你喜欢
        • 2016-09-17
        • 2014-01-09
        • 2018-09-17
        • 2020-11-04
        • 2018-01-25
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多