Reputation: 1058
I am trying to create a table that has individual rows that toggle when you click a button, in this case its 'View'. The table is constructed with a for loop for an array. I have managed to get it working when I have data already loaded, however when I push data to the array the toggle doesn't work.
How do I get the rows to toggle when 'View' is clicked?
Thanks!
Here is a JSBin
Below is my code:
HTML
<div id="app">
<button type="button" class="btn btn-primary" @click="sites.push( {
sku: '1005',
purchasePrice: 4.50
})">Add Data</button>
<div class="table-wrapper">
<table class="table table-hovered">
<thead>
<tr>
<th>SKU</th>
<th>Purchase Price</th>
</tr>
</thead>
<tbody>
<template v-for="item in sites" >
<tr>
<th>{{ item.sku }}</th>
<th> {{ item.purchasePrice }}</th>
<th id="toggle" @click="addEvent($event, item)">
View
</th>
</tr>
<template v-if="item.showTab">
<tr>
<th class="subCol subTable" colspan="6">
Content
</th>
</tr>
</template>
</template>
</tbody>
</table>
</div>
</div>
Vue JavaScript
new Vue({
el: '#app',
data: {
sites: [
{
sku: "10001",
purchasePrice: "4.50",
showTab: false,
},
{
sku: "10002",
purchasePrice: "4.50",
showTab: false,
},
{
sku: "10003",
purchasePrice: "4.50",
showTab: false,
}
],
newData: [],
},
methods: {
addEvent(event, item, type, target) {
this.newData = [];
for (let i = 0; i < this.sites.length; i++) {
if (event.target.id == "toggle") {
item.showTab = !item.showTab;
}
}
this.newData.push(this.sites);
},
}
});
Upvotes: 0
Views: 619
Reputation: 1205
There some little mistakes leading to your unexpected result.
First of all, when an item is added to your array, the showTab
property is not included.
Consider replacing this snippet:
<button type="button" class="btn btn-primary" @click="sites.push( {
sku: '1005',
purchasePrice: 4.50
})">
Add Data
</button>
By this :
<button type="button" class="btn btn-primary" @click="sites.push( {
sku: '1005',
purchasePrice: 4.50,
showTab: false
})">
Add Data
</button>
Then, when want to trigger the toggle, instead of targeting the element you want to toggle, you are going through the array and updating all elements, because all of them fullfil the condition if (event.target.id == "toggle")
.
To my understanding, what you want to achieve is toggling only one element. To achieve that, you should replace this :
addEvent(event, item, type, target) {
this.newData = [];
for (let i = 0; i < this.sites.length; i++) {
if (event.target.id == "toggle") {
item.showTab = !item.showTab;
}
}
this.newData.push(this.sites);
}
By the snippet below :
addEvent(event, item, type, target) { // There are some unused arguments here, consider removing them if they are not needed
item.showTab = !item.showTab;
}
You could even update the item toggle mode directly on the html the following way :
<th id="toggle" @click="item.showTab = !item.showTab">
View
</th>
Upvotes: 1