Looking for an example:
How to show hide columns of vuetify data table using v-select list
I have created something similar, but I'm facing an issue where the table doesn't refresh when changing the header data:
https://codepen.io/Meff1/pen/vYLNYWR
<template>
<v-container>
<v-select v-model="value" :items="headers" label="Select Item" multiple return-object>
<template v-slot:selection="{ item, index }">
<v-chip v-if="index === 0">
<span>{{ item.text }}</span>
</v-chip>
<span v-if="index === 1">(+{{ value.length - 1 }} others)</span>
</template>
</v-select>
<br />
<v-data-table :headers="this.selectedHeaders" :items="xyz">
<template slot="items" slot-scope="props">
<td
v-for="header in this.selectedHeaders"
:key="header"
v-show="show[header.text]"
>{{ props.item[header.value] }}</td>
</template>
</v-data-table>
</v-container>
</template>
<script lang="ts">
const charData: Array<object> = [
{
id: 10,
firstName: "Kyle",
lastName: "Broflovski",
saying: "Goddamnit Cartman!"
},
{
id: 20,
firstName: "Eric",
lastName: "Cartman",
saying: "Screw you guys, Im going home"
},
{
id: 30,
firstName: "Stanley",
lastName: "Marsh",
saying: "WTF"
},
{
id: 40,
firstName: "Kenny",
lastName: "McCormick",
saying: "hmhpmhphmphmhp"
}
];
let headers: Array<object> = [];
let selectedHeaders: Array<object> = [];
const show: any = {};
const value: Array<object> = [];
let selectedData: Array<object> = [];
import Vue from "vue";
export default Vue.extend({
name: "PFTable",
data: () => ({
charData,
headers,
value,
selectedHeaders,
selectedData,
show
}),
computed: {
xyz: () => {
return selectedData;
}
},
watch: {
value(val) {
selectedHeaders = val;
const res = selectedHeaders.map(x => x.text);
selectedData = [];
for (const k in charData) {
const element: any = charData[k];
const filtered = Object.keys(element)
.filter(key => res.includes(key))
.reduce((obj: any, key: any) => {
obj[key] = element[key];
return obj;
}, {});
selectedData.push(filtered);
}
}
},
beforeCreate() {
headers = [];
const headersData = Object.keys(charData[0]);
headersData.forEach(element => {
headers.push({ text: element, value: element });
});
selectedHeaders = headers;
selectedData = charData;
}
});
</script>
I am struggling to figure out how to toggle the visibility of columns based on selections made in the select list.
I have an array called selectedData which is linked to the data table as its items property. selectedData is a computed property and gets updated in the watcher method when changes are made to the select list. However, the data table does not reflect these changes. Shouldn't the computed property re-evaluate whenever the underlying property changes?