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

标签 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> 

我怎样才能做到这一点?

最佳答案

实际上,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>

关于javascript - 根据复选框隐藏/显示表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48574586/

相关文章:

javascript - 使用 css :not[value =""] 在 vuejs 中输入值

javascript - 使用 v-model 在 v-for 数组中搜索 - Vue.js

javascript - 为什么 Vue 的提供和注入(inject)功能会出现警告?

javascript - 带有 '&' 的参数打破了 $.ajax 请求

javascript - JS Click 上的 PHP 函数?

javascript - 就地编辑链接

javascript - 在运行时创建时移动元素时出错

vue.js - 将 vue-router 组件解释为一个函数

javascript - axios在vue中嵌套json

vue.js - vuejs组件的样式对其他组件来说是全局的吗