0👍
First off, your table template could be much simpler. Vuetify will actually produce the correct header for you without your having to specify a template for it. Your JavaScript could be much simpler, as well:
<template>
<v-data-table
v-model="selected"
:headers="headers"
:items="desserts"
item-key="name"
select-all
>
<template #items="props">
<tr :active="props.selected" @click="props.selected = !props.selected">
<td>
<v-checkbox
:input-value="props.selected"
primary
hide-details
></v-checkbox>
</td>
<td>{{ props.item.name }}</td>
<td class="text-xs-center">
{{ props.item.calories }}
</td>
<td class="text-xs-center">
{{ props.item.fat }}
</td>
</tr>
</template>
</v-data-table>
</template>
<script>
export default {
name: 'MyVuexDataTable',
computed: {
...mapState(['desserts', 'headers']),
selected: {
get () {
return this.$store.state.selected
},
set (selected) {
this.$store.dispatch('setSelected', selected)
},
},
},
}
</script>
You also don’t have to write your own function to do the toggling. Vuetify will handle that for you. As for the store, what you had is mostly fine, except you need to be careful when mutating objects and arrays. Vue’s reactivity system won’t react to changes of properties so it’s best to use the built-in Vue.set()
function.
const SET_SELECTED = 'SET_SELECTED' // mutation type
const store = new Vuex.Store({
state: {
selected: [],
desserts: [
{
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0,
carbs: 24,
protein: 4.0,
iron: '1%',
},
{
name: 'Ice cream sandwich',
calories: 237,
fat: 9.0,
carbs: 37,
protein: 4.3,
iron: '1%',
},
{
name: 'Eclair',
calories: 262,
fat: 16.0,
carbs: 23,
protein: 6.0,
iron: '7%',
},
],
headers: [
{ text: 'Dessert (100g serving)', align: 'left',value: 'name'},
{ text: 'Calories', value: 'calories' },
{ text: 'Fat (g)', value: 'fat' },
],
},
actions: {
setSelected ({ commit }, selected) {
commit(SET_SELECTED, selected)
}
},
mutations: {
[SET_SELECTED] (state, selected) {
Vue.set(state, 'selected', [...selected])
}
},
})
Here’s a codepen with a fully working example. It’s slightly different than you’ll use in your project because it all runs in the browser and there is no webpack build system.
0👍
This seems to be working for me.
Header checkbox html code.
<v-simple-checkbox
:value="selected.length == records.length"
:indeterminate="selected.length>0 && selected.length<records.length"
:ripple="false"
@click="toggleSelectAll"
></v-simple-checkbox>
Toggle All function.
toggleSelectAll() {
if (this.selected.length < this.records.length)
this.selected = this.records;
else this.selected = [];
}