I've been playing around with Bootstrap Vue and tables.
My problem is as follows: I have several tables that are dynamically loaded on a page, and users should be able to select items on each of those tables. All selections should then be concatenated into one array that I can then display at the top of the page.
So far I've added the following to each of the tables:
@row-selected="onRowSelected"
As well as the following method:
methods: {
onRowSelected(items) {
items.forEach((item) => {
if (!this.selectedHashtags.includes(item.hashtag)) {
this.selectedHashtags.push(item.hashtag);
}
})
},
}
The issue is that as soon as I deselect an item from the table it doesn't remove it from the array, and I'm struggling to find a way to make this work.
Unfortunately the @row-selected
event doesn't send the ID / ref of the table, and I can't find find a method of getting all the selected rows from each individual table. That way I could just loop through all the this.$refs
and get all the selected rows and bundle them together on every row-click.
Essentially the easiest way would be if there was a way to programmatically obtain all the selected items from a table?
Any thoughts on what the best way to achieve this might be?
Probably the easiest way would be to store the selected value together with a unique key of each table. You would then call the method like with the keyword $event
(see the documentation):
@row-selected="onRowSelected('table1', $event)"
You could also wrap an inline function in the template to achieve the same result:
@row-selected="(items) => onRowSelected('table1', items)"
Then, you would store the items in an object depending on the table key:
onRowSelected(tableKey, items) {
// clears the list of this table key and overwrites it with the current entries
this.selectedHashtags[tableKey] = items;
}
You can then define a computed variable to retrieve all selected hashtags (over all tables):
allSelectedHashtags() {
const allSelectedHashtags = [];
Object.keys(this.selectedHashtags).forEach(tableArray => {
allSelectedHashtags.concat(tableArray);
});
return allSelectedHashtags;
}