根据复选框隐藏/显示表格行

时间:2018-02-02 01:55:15

标签: javascript vue.js vuejs2

我有一些复选框,我想用它来显示/隐藏表格中的行,其内容与所选复选框的值相匹配。

复选框:

<input type='checkbox' name='foo1' value='foo1' v-model="selectedType"/> foo1 &nbsp;
<input type='checkbox' name='foo2' value='foo2' v-model="selectedType"/> foo2 &nbsp;
<input type='checkbox' name='bar1' value='bar1' v-model="selectedType"/> bar1 &nbsp;

我有一个对象,我曾经用v-for构建一个表:

<table>
    <template v-for="sampleItem in sampleObj">
        <tr>
           <td>{{sampleItem.item}}</td>
           <td>{{sampleItem.description}}</td>
        </tr>
    </template>
</table>

JS:

new Vue({
    data: {
        selectedType: [],
        sampleObj = [{'item': 'item1', 'description': 'foo1 blah'},
                     {'item': 'item2', 'description': 'foo2 vlah'},
                     {'item': 'item3', 'description': 'bar1 nlah'},
                     {'item': 'item4', 'description': 'bar2 clah'},
        ];
    }
});

默认情况下,取消选中复选框。因此,只有具有描述为“bar2”的单元格的行最初可见。然后,当我切换其他复选框时,其他行也应该变得可见(描述与逐字复选框值不匹配,但后面跟着几个字。我可以在这里做一些字符串处理)。

我以为我可以在标签中使用v-if指令来查看selectedType的值,但我不知道如何才能实现这一点。

伪代码:

<tr v-if="selectedType ~= /sampleItem.description/">
...
...
</tr> 

我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

v-if实际上有两个条件:如果没有与描述匹配的复选框,则需要显示该行;如果有复选框,则必须进行检查。

我将复选框值放入它们所属的数据中。我做了一个测试方法。它首先查看描述是否与任何复选框值匹配,然后检查是否选择了匹配的值。

new Vue({
  el: '#app',
  data: {
    selectedType: [],
    sampleObj: [{
        'item': 'item1',
        'description': 'foo1 blah'
      },
      {
        'item': 'item2',
        'description': 'foo2 vlah'
      },
      {
        'item': 'item3',
        'description': 'bar1 nlah'
      },
      {
        'item': 'item4',
        'description': 'bar2 clah'
      },
    ],
    cbValues: ['foo1', 'foo2', 'bar1']
  },
  methods: {
    isVisible(row) {
      const matchedValue = this.cbValues.find(v => row.description.indexOf(v) >= 0);

      if (!matchedValue) {
        return true;
      }
      return this.selectedType.includes(matchedValue);
    }
  }
});
td {
  border: thin solid black;
}
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <div v-for="val in cbValues">
    <label>
      <input type='checkbox' :value='val' v-model="selectedType"> 
      {{val}}
    </label>
  </div>
  <table>
    <template v-for="sampleItem in sampleObj">
        <tr v-if="isVisible(sampleItem)">
           <td>{{sampleItem.item}}</td>
           <td>{{sampleItem.description}}</td>
        </tr>
    </template>
  </table>
</div>

相关问题