[英]Hide/show table rows based on checkbox
我有一些復選框,我想使用它們來顯示/隱藏表中的行,這些表的內容與所選復選框的值匹配。
復選框:
<input type='checkbox' name='foo1' value='foo1' v-model="selectedType"/> foo1
<input type='checkbox' name='foo2' value='foo2' v-model="selectedType"/> foo2
<input type='checkbox' name='bar1' value='bar1' v-model="selectedType"/> bar1
我有一個用於使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.