Vuetify data table with nested data and v-slot:item - vue.js

I would like to create a Vuetify table with nested data. The problem is that v-slot:item doesn't seem to work with nested data.
This is my code: https://codepen.io/blakex/pen/XWKWjaE
<v-data-table :headers="headers" :items="desserts">
<template v-slot:item.calories="{ item }">
<td>Slot works: {{ item.calories }}</td>
</template>
<template v-slot:item.nested.nestedCalories="{ item }">
<td>Nested slot works: {{ item.nested.nestedCalories }}</td>
</template>
</v-data-table>
data () {
return {
headers: [
{ text: 'Dessert', value: 'name' },
{ text: 'Calories', value: 'calories' },
{ text: 'Nested Calories', value: 'nested.nestedCalories' },
],
desserts: [
{
name: 'Yogurt',
calories: 100,
nested: { nestedCalories: 100 },
},
...
],
}
}
As you can see, the v-slot:item.nested.nestedCalories doesn't work.
Does anyone know what is missing?

This doesn't seem to be mentioned in the DOM Template Parsing Caveats, but HTML tags and attributes are not case-sensitive. In Codepen you're using the DOM as a template, so the v-slot:item.nested.nestedCalories attribute becomes lowercase (v-slot:item.nested.nestedcalories). If you change the value in headers to lowercase you'll see that it works.
To avoid this you should always use string templates with Vue. String templates can be:
.vue files
The template option
<script type="text/x-template"> like the vuetify codepen template uses
Your code written with x-template looks like this:
<div id="app"></div>
<script type="text/x-template" id="app-template">
<v-app>
<v-data-table
:headers="headers"
:items="desserts"
:items-per-page="5"
class="elevation-1"
>
<template v-slot:item.calories="{ item }">
<td>Slot works: {{ item.calories }}</td>
</template>
<template v-slot:item.nested.nestedCalories="{ item }">
<td>Nested slot works: {{ item.nested.nestedCalories }}</td>
</template>
</v-data-table>
</v-app>
</script>
<script>
const App = {
template: '#app-template',
data: () => ({
headers: [
{ text: 'Dessert', value: 'name' },
{ text: 'Calories', value: 'calories' },
{ text: 'Nested Calories', value: 'nested.nestedCalories' },
],
desserts: [
{
name: 'Yogurt',
calories: 100,
nested: { nestedCalories: 100 },
},
{
name: 'Ice cream',
calories: 200,
nested: { nestedCalories: 200 },
},
{
name: 'Eclair',
calories: 300,
nested: { nestedCalories: 300 },
},
],
})
}
new Vue({
vuetify: new Vuetify(),
render: h => h(App)
}).$mount('#app')
</script>

Related

Pass component as prop in Vue JS

Intro: I am exploring Vue Js and got stuck while trying to make a dynamic data table component the problem I am facing is that I cannot pass a component via props and render it inside a table.
Problem: So basically what I am trying to do is to pass some custom component from headers prop in v-data-table such as:
headers = [
{ text: 'Name', value: 'name' },
{
text: 'Phone Number',
value: 'phone_number',
render: () => (
<div>
<p>Custom Render</p>
</div>
)
},
{ text: 'Actions', value: 'actions' }
]
So from the code above we can see that I want to render that paragraph from the render function inside Phone Number header, I did this thing in React Js before, but I cannot find a way to do it in Vue Js if someone can point me in the right direction would be fantastic. Thank you in advance.
You have 2 options - slots and dynamic components.
Let's first explore slots:
<template>
<v-data-table :items="dataItems" :headers="headerItems">
<template slot="item.phone_number" slot-scope="{item}">
<v-chip>{{ item.phone_number }}</v-chip>
</template>
<template slot="item.company_name" slot-scope="{item}">
<v-chip color="pink darken-4" text-color="white">{{ item.company_name }}</v-chip>
</template>
</v-data-table>
</template>
The data table provides you slots where you can customize the content. If you want to make your component more reusable and want to populate these slots from your parent component - then you need to re-expose these slots to the parent component:
<template>
<v-data-table :items="dataItems" :headers="headerItems">
<template slot="item.phone_number" slot-scope="props">
<slot name="phone" :props="props" />
</template>
<template slot="item.company_name" slot-scope="props">
<slot name="company" :props="props" />
</template>
</v-data-table>
</template>
If you don't know which slots will be customized - you can re-expose all of the data-table slots:
<template>
<v-data-table
:headers="headers"
:items="items"
:search="search"
hide-default-footer
:options.sync="pagination"
:expanded="expanded"
class="tbl_manage_students"
height="100%"
fixed-header
v-bind="$attrs"
#update:expanded="$emit('update:expanded', $event)"
>
<!-- https://devinduct.com/blogpost/59/vue-tricks-passing-slots-to-child-components -->
<template v-for="(index, name) in $slots" v-slot:[name]>
<slot :name="name" />
</template>
<template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">
<slot :name="name" v-bind="data" />
</template>
<v-alert slot="no-results" color="error" icon="warning">
{{ $t("no_results", {term: search}) }}"
</v-alert>
<template #footer="data">
<!-- you can safely skip the "footer" slot override here - so it will be passed through to the parent component -->
<table-footer :info="data" #size="pagination.itemsPerPage = $event" #page="pagination.page = $event" />
</template>
</v-data-table>
</template>
<script>
import tableFooter from '#/components/ui/TableFooter'; // you can safely ignore this component in your own implementation
export default
{
name: 'TeacherTable',
components:
{
tableFooter,
},
props:
{
search:
{
type: String,
default: ''
},
items:
{
type: Array,
default: () => []
},
sort:
{
type: String,
default: ''
},
headers:
{
type: Array,
required: true
},
expanded:
{
type: Array,
default: () => []
}
},
data()
{
return {
pagination:
{
sortDesc: [false],
sortBy: [this.sort],
itemsPerPageOptions: [25, 50, 100],
itemsPerPage: 25,
page: 1,
},
};
},
watch:
{
items()
{
this.pagination.page = 1;
},
sort()
{
this.pagination.sortBy = [this.sort];
this.pagination.sortDesc = [false];
},
}
};
</script>
Dynamic components can be provided by props:
<template>
<v-data-table :items="dataItems" :headers="headerItems">
<template slot="item.phone_number" slot-scope="{item}">
<component :is="compPhone" :phone="item.phone_number" />
</template>
<template slot="item.company_name" slot-scope="{item}">
<component :is="compCompany" :company="item.company_name" />
</template>
</v-data-table>
</template>
<script>
export default
{
name: 'MyTable',
props:
{
compPhone:
{
type: [Object, String], // keep in mind that String type allows you to specify only the HTML tag - but not its contents
default: 'span'
},
compCompany:
{
type: [Object, String],
default: 'span'
},
}
}
</script>
Slots are more powerful than dynamic components as they (slots) use the Dependency Inversion principle. You can read more in the Markus Oberlehner's blog
Okay, I don't believe this is the best way possible but it works for me and maybe it will work for someone else.
What I did was I modified the headers array like this:
headers = [
{ text: 'Name', align: 'start', sortable: false, value: 'name' },
{
text: 'Phone Number',
key: 'phone_number',
value: 'custom_render',
render: Vue.component('phone_number', {
props: ['item'],
template: '<v-chip>{{item}}</v-chip>'
})
},
{ text: 'Bookings', value: 'bookings_count' },
{
text: 'Company',
key: 'company.name',
value: 'custom_render',
render: Vue.component('company_name', {
props: ['item'],
template:
'<v-chip color="pink darken-4" text-color="white">{{item}}</v-chip>'
})
},
{ text: 'Actions', value: 'actions', sortable: false }
]
And inside v-data-table I reference the slot of custom_render and render that component there like this:
<template v-slot:[`item.custom_render`]="{ item, header }">
<component
:is="header.render"
:item="getValue(item, header.key)"
></component>
</template>
To go inside the nested object like company.name I made a function which I called getValue that accepts 2 parametes, the object and the path to that value we need which is stored in headers array as key (ex. company.name) and used loadash to return the value.
getValue function:
getValue (item: any, path: string): any {
return loadash.get(item, path)
}
Note: This is just the initial idea, which worked for me. If someone has better ideas please engage with this post. Take a look at the props that I am passing to those dynamic components, note that you can pass more variables in that way.

Sort Vue data table by selection

Is there a way to sort a v-data-table by the selection column?
I would like to multisort my v-data-table. First by selection, so the selected ones are always on top and second by name. So far I got this:
<template>
<v-app>
<div id="app">
<v-data-table
:headers="tableHeaders"
:items="selectables"
:show-select="true"
:sort-by="['isSelected', 'name']"
multi-sort
v-model="output"
return-object
>
</v-data-table>
</div>
</v-app>
</template>
<script>
export default {
data() {
return {
output: {},
tableHeaders: [
{
text: "name",
value: "name",
},
],
selectables: [
{
name: "toni",
},
{
name: "hans",
},
{
name: "fritz",
},
],
};
},
};
</script>

How can I sort a v-data-table by default?

I can't seem to get default sorting to work. All I can see for the argument custom-sort in the documentation is that it's a "Function used to sort items", but I don't know in what way. I can imagine many. Is it called for an initial sort? It seems to return a list of items, but when I try to create one, I get an error saying this.customSort is not a function.
<template>
<v-data-table
:headers="headers"
:items="reports"
hide-default-footer>
<template v-slot:item.requested="{ item }">
{{ datetimeToDistance(item.requested) }}
</template>
</v-data-table>
</template>
<script>
export default {
name: 'Reports',
data () {
return {
customSort: (items,index,isDesc) => console.log("never called"),
reports: [{name:"a",requested:"2020-01-01T00:00:00Z"}.{name:"b",requested:"2020-02-02T00:00:00"}],
}
},
computed: {
headers () {
return [
{text: "Name", value: "name"},
{text: "Report Type", value: "report_type"},
{text: "Requested", value: "requested", sort: (a,b) => a.localeCompare(b) },
];
},
}
}
</script>
My sorting works if you click on the links. All I really want here is to say: "When the page first loads, sort by 'requested' as though the user clicked that one initially. Then let them change the ordering."
Note: The datetimeToDistance is just a function which calls a library and isn't too important. It's just that the output of that column is not directly in the objects.
Use the sort-by and the sort-desc properties with the .sync option, and set the desired values in data.
<template>
<div>
<v-data-table
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
></v-data-table>
</div>
</template>
<script>
export default {
data () {
return {
sortBy: 'fat',
sortDesc: false,
},
}
</script>
https://vuetifyjs.com/en/components/data-tables/#external-sorting
I usually sort v-datatable in the pagination directive as below:
<template>
<v-data-table :headers="headers" :items="reports" :pagination.sync="pagination" hide-default-footer>
<template v-slot:item.requested="{ item }">
{{ datetimeToDistance(item.requested) }}
</template>
</v-data-table>
</template>
<script>
export default {
name: 'Reports',
data() {
return {
customSort: (items, index, isDesc) => console.log("never called"),
reports: [{ name: "a", requested: "2020-01-01T00:00:00Z" }.{ name: "b", requested: "2020-02-02T00:00:00" }],
pagination: { sortBy: 'requested', descending: true, rowsPerPage: 10 }
}
},
computed: {
headers() {
return [
{ text: "Name", value: "name" },
{ text: "Report Type", value: "report_type" },
{ text: "Requested", value: "requested", sort: (a, b) => a.localeCompare(b) },
];
},
}
}
</script>

Vuetify checkboxes array checks all boxes when list changes

I'm pretty new to both vue and vuetify so there might be a few horrible lines in my code, but I'm really struggling with this one and a bit of help would be nice.
I have an array of checkboxes generated with a v-for loop on an "items" array. This array of checkboxes is attached to a model array just like this example from the vuetify documentation.
It looks like the code below.
The problem is : if I change the items array, even when the model array is still empty, all checkboxes end up checked.
Here is my template :
<div id="app">
<v-app>
<v-content>
<v-container>
<div>
<v-list>
<v-list-item
v-for="item in items" :key="item.id"
>
<v-checkbox
v-model="model" :label="item.name"
:value="item"
:value-comparator="comparator"
></v-checkbox>
</v-list-item>
</v-list>
<v-btn #click="updateItems">Change elements</v-btn>
</div>
</v-container>
</v-content>
</v-app>
</div>
and the script
new Vue({
el: "#app",
vuetify: new Vuetify(),
data() {
return {
model: [],
items: [
{
id: 1,
name: "Item1"
},
{
id: 2,
name: "Item2"
},
{
id: 3,
name: "Item3"
},
{
id: 4,
name: "Item4"
}
]
};
},
methods: {
comparator(a, b) {
return a.id == b.id;
},
updateItems() {
this.items = [
{
id: 1,
name: "Element1"
},
{
id: 2,
name: "Element2"
},
{
id: 3,
name: "Element3"
},
{
id: 4,
name: "Element4"
}
]
}
}
});
And a codepen is way easier to understand
I've been struggling with this issue for a while now, if you have any idea, that would be welcome. Thank you !
EDIT : I had made a mistake in my code. Fixed it. The question is still the same though.
There are few bugs in this code,
from the below checkbox
<v-checkbox
v-model="model" :label="item.name"
:value="item"
:value-comparator="comparator"
></v-checkbox>
:value-comparator is triggers when you click on checkbox, it tries to
match with all other value and returns true only for the selected id
"comparator" function is not available in your methods, replace "valueCompare" method with "comparator"
when you click on change elements, it resets items array but you are not reseting the model
working codepen : https://codepen.io/chansv/pen/rNNyBgQ
Added fixs and final code looks like this
<div id="app">
<v-app>
<v-content>
<v-container>
<div>
<v-list>
<v-list-item
v-for="item in items" :key="item.id"
>
<v-checkbox v-model="model" :label="item.name"
:value="item"
:value-comparator="comparator"
></v-checkbox>
</v-list-item>
</v-list>
<v-btn #click="updateItems">Change elements</v-btn>
</div>
</v-container>
</v-content>
</v-app>
</div>
// Looking for the v1.5 template?
// https://codepen.io/johnjleider/pen/GVoaNe
new Vue({
el: "#app",
vuetify: new Vuetify(),
data() {
return {
model: [],
items: [
{
id: 1,
name: "Item1"
},
{
id: 2,
name: "Item2"
},
{
id: 3,
name: "Item3"
},
{
id: 4,
name: "Item4"
}
]
};
},
methods: {
comparator(a, b) {
console.log(a, b);
return a.id == b.id;
},
updateItems() {
this.model = [];
this.items = [
{
id: 1,
name: "Element1"
},
{
id: 2,
name: "Element2"
},
{
id: 3,
name: "Element3"
},
{
id: 4,
name: "Element4"
}
]
}
}
});

How do I use "custom filter" prop in data tables in vuetify? or How do I create a custom filter to filter by headers?

As of date of posting, I cannot find any documentation to use the "custom filter" prop in data tables.
I just want to create a custom filter to filter my data table by headers.
I have a dropdown, and when user click on one of the options for the dropdown, it will filter the list for one specific header.
Example:
Dropdown options:
Food type: fruit, meat, vegetable
Bakchoi (vegetable)
Pork (meat)
Chicken Thigh (meat)
watermelon (fruit)
If I select dropdown as meat, it should only show me pork and chicken thigh.
Looking at the code on Github1, it looks like the customFilter prop is used to overwrite the default method used to determine how the filter prop is applied to the items in the table.
The default customFilter method applies the filter function to each property name of each item object and filters out any items that don't include one property name that passes the filter:
customFilter: {
type: Function,
default: (items, search, filter) => {
search = search.toString().toLowerCase()
return items.filter(i => (
Object.keys(i).some(j => filter(i[j], search))
))
}
},
You might want to overwrite this function if you wanted to prevent any columns from being included in the filter or if there were specific rows that you always wanted to prevent from being filtered out.
You'll notice that the method also depends on the search prop, which must be a string.
All that said, you really don't need to use that prop for what you want to do. You should just make a computed property to filter the items based on your dropdown value and pass that computed property as the items prop.
Here's an example:
new Vue({
el: '#app',
data() {
return {
food: [
{ name: 'Bakchoi', type: 'vegetable', calories: 100 },
{ name: 'Pork', type: 'meat', calories: 200 },
{ name: 'Chicken Thigh', type: 'meat', calories: 300 },
{ name: 'Watermelon', type: 'fruit', calories: 10 },
],
headers: [
{ text: 'Name', align: 'left', value: 'name' },
{ text: 'Food Type', align: 'left', value: 'type' },
{ text: 'Calories', align: 'left', value: 'calories' },
],
foodType: null,
};
},
computed: {
filteredItems() {
return this.food.filter((i) => {
return !this.foodType || (i.type === this.foodType);
})
}
}
})
<script src="https://unpkg.com/vue#2.4.2/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify#0.15.2/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify#0.15.2/dist/vuetify.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
<div id="app">
<v-app>
<v-select
label="Food Type"
:items="['vegetable', 'meat', 'fruit']"
v-model="foodType"
></v-select>
<v-data-table
:headers="headers"
:items="filteredItems"
hide-actions
>
<template slot="items" scope="{ item }">
<td>{{ item.name }}</td>
<td>{{ item.type }}</td>
<td>{{ item.calories }}</td>
</template>
</v-data-table>
</v-app>
</div>
This answer was written when Vuetify was at v0.15.2. The source code for the VDataTable component at that version can be found here.
You can also go the customFilter approach like this, I've restricted the search to the type field.
new Vue({
el: '#app',
data() {
return {
food: [
{ name: 'Bakchoi', type: 'vegetable', calories: 100 },
{ name: 'Pork', type: 'meat', calories: 200 },
{ name: 'Chicken Thigh', type: 'meat', calories: 300 },
{ name: 'Watermelon', type: 'fruit', calories: 10 },
],
headers: [
{ text: 'Name', align: 'left', value: 'name' },
{ text: 'Food Type', align: 'left', value: 'type' },
{ text: 'Calories', align: 'left', value: 'calories' },
],
search: '',
};
},
methods: {
customFilter(items, search, filter) {
search = search.toString().toLowerCase()
return items.filter(row => filter(row["type"], search));
}
}
})
<script src="https://unpkg.com/vue#2.4.2/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify#0.15.2/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify#0.15.2/dist/vuetify.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
<div id="app">
<v-app>
<v-select
label="Food Type"
:items="['vegetable', 'meat', 'fruit']"
v-model="search"
></v-select>
<v-data-table
:headers="headers"
:items="food"
:search="search"
:custom-filter="customFilter"
hide-actions
>
<template slot="items" scope="{ item }">
<td>{{ item.name }}</td>
<td>{{ item.type }}</td>
<td>{{ item.calories }}</td>
</template>
</v-data-table>
</v-app>
</div>
In my case I have 2 different way of filtering which are search bar and drop down. I tried to use custom-filter for both of them, but it doesn't work, so I came up with another approach
<v-text-field v-model="search" label="Label"></v-text-field>
<v-select
v-model="select"
:items="food"
item-text="type"
item-value="type"
:label="Types"
#change="filterFoodUsingDropDown"
>
</v-select>
<v-data-table
:search="search"
:headers="headers"
:items="food"
:custom-filter="filterFoodUsingSearchbar"
>
data() {
return {
food: [
{ name: 'Bakchoi', type: 'vegetable', calories: 100 },
{ name: 'Pork', type: 'meat', calories: 200 },
{ name: 'Chicken Thigh', type: 'meat', calories: 300 },
{ name: 'Watermelon', type: 'fruit', calories: 10 },
],
headers: [
{ text: 'Name', align: 'left', value: 'name' },
{ text: 'Food Type', align: 'left', value: 'type' },
{ text: 'Calories', align: 'left', value: 'calories' },
],
search: '',
select: '',
};
},
methods: {
filterFoodUsingSearchbar(items, search, filter) {
// Condition
}
filterFoodUsingDropDown() {
if (this.select !== '') {
// In this case I use vuex to store the original data of the
food so that all the data is still exist even we filtered it out
this.food = this.$store.state.food.filter((item) => item.type === this.select)
}
}