How to style a data table td in Vuetify? - vuetify.js

Good Afternoon.
I'm trying to build a stylized table with "v-data-table", without being used to it. Mainly put style into second or third cell (table, tr, td). I don't find the solution for my problem. Help me, please.
thanks.

You can use the item-class attributes to style every row
Property on supplied items that contains item’s row class or function that takes an item as an argument and returns the class of corresponding row
It works as the following :
It takes a function as argument that return a class depending on the row.
If you want to return a specific class depending on the item use it like this :
<template>
<v-datad-table :item="items" :item-class="getMyClass"></v-data-table>
</template>
<script>
methods: {
getMyClass(item){
// here define your logic
if (item.value === 1) return "myFirstClass"
else return "mySecondClass"
}
}
</script>
If you want to always give the same class you can just return the class you want to give (note that this is the same as stylized the td of the table using css)
<template>
<v-data-table :items="items" :item-class="() => 'myClass'"></v-data-table>
</template>
In your case, you can add an index to your data using a computed property and added a class based on the index
computed: {
myItemsWithIndex(){
retunr this.items.map((x, index) => {...x, index: index})
}
}
methods: {
getMyClass(item){
if(item.index === 2 || item.index === 3) return "myClass"
}
}
Working example
new Vue({
el: "#app",
vuetify: new Vuetify(),
data: () => {
return {
items: [
{name: "foo"},
{name: "bar"},
{name: "baz"},
{name: "qux"},
{name: "quux"},
{name: "corge"},
{name: "grault"},
],
headers: [{ text: 'Name', value: 'name'}],
}
},
computed: {
itemsWithIndex(){
return this.items.map((item, index) => ({ ...item, index:index }))
}
},
methods: {
getMyClass(item){
if(item.index === 2 || item.index === 3){
return "myClass"
} else return
}
}
})
.myClass {
background: red
}
<script src="https://unpkg.com/vue#2.x/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify#2.6.4/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify#2.6.4/dist/vuetify.min.css" />
<div id="app" data-app>
<v-data-table :items="itemsWithIndex" :headers="headers" :item-class="getMyClass"></v-data-table>
</div>

I'd bet that what you're trying to achieve can be done using named slots
See this example from the docs. Basically, the template tag you see in the example will become whatever node is 'above it' (which it really isn't because it takes its place, but you get the point). For instance, in the case of data-tables, <template #item="{ item }">... represents every <td> of your table. Then you can use the destructured item and apply some logic to it to still of modify you table as you will.
Don't forget to upvote/validate the answer if it helped your to solve your issue, comment if you need more details and welcome to Stack!

There are also the possibility to use cellClass, which is part of the headers.
The image is from https://vuetifyjs.com/en/api/v-data-table/#props
As computed property i have:
headers() {
return [
{ text: this.$t('Name'), align: 'left', sortable: true, value: 'name', cellClass:'select' },
{ text: 'CVR', sortable: false, value: 'cvrno' },
{ text: this.$t('Updated At'), sortable: false, value: 'updatedAt' }
]
},
and by v-data-table tag looks like:
<v-data-table
v-model="selected"
:headers="headers"
:items="customerFiltered"
:loading="loadingCustomers"
:items-per-page="-1"
selected-key="id"
show-select
hide-default-footer
fixed-header
>

Related

How to alter a value in a v-data-table

I am new to vuetify and I'm trying to take the value in a column of a v-data-table and convert it to it's text equivalent, but can't find out how to do it.
headers: [
{ text: 'Name', value: 'name' },
{ text: 'Type', value: 'typeName(type)' },
]
I have tried typeName as a computed value and as a method:
typeName(typId) {
return ...
},
How do I get this to work?
Yes, you can format the column value by adding a explict function
Here is the working codepen which reverse the value of first column: https://codepen.io/chansv/pen/GRRjaqj?editors=1010
If you have headers type, no need to call the function from here,
instead we need to call from column by adding a template
headers: [
{ text: 'Name', value: 'name' },
{ text: 'Type', value: 'type' },
]
In the HTML , add a template with slot points to body
<v-data-table
:headers="headers"
:items="items" >
<template v-slot:body="{items}">
<tbody>
<tr v-for="item in items" :key="item.name">
<td>{{item.name}}</td>
<td>{{typeName(item.type)}}</td>
</tr>
</tbody>
</template>
</v-data-table>
Inside data property add a property typeName
data() {
return {
typeName: (type) => type.substring(2),
}
}

Auto select rows in v-data-table

I would like to programmatically checkmark a row in a v-data-table when an external listener notifies me of a particular value.
As an example, here is a Vuetify selectable table: https://vuetifyjs.com/en/components/data-tables#selectable-rows
In the example, If I were passed the value of 'Gingerbread' after the table and its data have already been instantiated, how would I programmatically select that corresponding row?
You can do this by pushing your values in your model like this:
HTML:
<div id="app">
<v-app id="inspire">
<v-btn #click="select">button</v-btn>
<v-data-table
v-model="selected"
:headers="headers"
:items="desserts"
:single-select="singleSelect"
item-key="name"
show-select
class="elevation-1"
>
<template v-slot:top>
<v-switch v-model="singleSelect" label="Single select" class="pa-3"></v-switch>
</template>
</v-data-table>
</v-app>
</div>
VueJS:
new Vue({
el: '#app',
vuetify: new Vuetify(),
methods: {
select: function() {
let result = this.desserts.find((dessert) => {
return dessert.name == 'Gingerbread'
})
this.selected.push(result)
}
},
data () {
return {
singleSelect: false,
selected: [],
headers: [
{ text: 'Dessert (100g serving)', value: 'name' },
{ text: 'Calories', value: 'calories' },
],
desserts: [
{ name: 'Gingerbread', calories: 356 },
{ name: 'Jelly bean', calories: 375 }
],
}
},
})
The v-data-table component has a property called filteredItems which you can use to add items to the selected array
<v-data-table v-model="selected":items="itemsArray" ref="table"></v-data-table>
function selectAll() {
this.$refs.table.filteredItems.map(item => {
if(...some condition...) {
this.selected.push(item)
}
})
}

Binding a v-data-table to a props property in a template

I have a vue component which calls a load method returning a multi-part json object. The template of this vue is made up of several sub-vue components where I assign :data="some_object".
This works in all templates except for the one with a v-data-table in that the v-for process (or the building/rendering of the v-data-table) seems to kick-in before the "data" property is loaded.
With an npm dev server if I make a subtle change to the project which triggers a refresh the data-table then loads the data as I expect.
Tried various events to try and assign a local property to the one passed in via "props[]". Interestingly if I do a dummy v-for to iterate through or simply access the data[...] property the subsequent v-data-table loads. But I need to bind in other rules based on columns in the same row and that doesn't work.
Parent/main vue component:
...
<v-flex xs6 class="my-2">
<ShipViaForm :data="freight"></ShipViaForm>
</v-flex>
<OrderHeaderForm :data="orderheader"></OrderHeaderForm>
<v-flex xs12>
<DetailsForm :data="orderdet" :onSubmit="submit"></DetailsForm>
</v-flex>
...
So in the above the :data property is assigned from the result below for each sub component.
...
methods: {
load(id) {
API.getPickingDetails(id).then((result) => {
this.picking = result.picking;
this.freight = this.picking.freight;
this.orderheader = this.picking.orderheader;
this.orderdet = this.picking.orderdet;
});
},
...
DetailsForm.vue
<template lang="html">
<v-card>
<v-card-title>
<!-- the next div is a dummy one to force the 'data' property to load before v-data-table -->
<div v-show="false">
<div class="hide" v-for='header in headers' v-bind:key='header.product_code'>
{{ data[0][header.value] }}
</div>
</div>
<v-data-table
:headers='headers'
:items='data'
disable-initial-sort
hide-actions
>
<template slot='items' slot-scope='props'>
<td v-for='header in headers' v-bind:key='header.product_code'>
<v-text-field v-if="header.input"
label=""
v-bind:type="header.type"
v-bind:max="props.item[header.max]"
v-model="props.item[header.value]">
</v-text-field>
<span v-else>{{ props.item[header.value] }}</span>
</td>
</template>
</v-data-table>
</v-card-title>
</v-card>
</template>
<script>
import API from '#/lib/API';
export default {
props: ['data'],
data() {
return {
valid: false,
order_id: '',
headers: [
{ text: 'Order Qty', value: 'ord_qty', input: false },
{ text: 'B/O Qty', value: 'bo_qty', input: false },
{ text: 'EDP Code', value: 'product_code', input: false },
{ text: 'Description', value: 'product_desc', input: false },
{ text: 'Location', value: 'location', input: false },
{ text: 'Pick Qty', value: 'pick_qty', input: true, type: 'number', max: ['ord_qty'] },
{ text: 'UM', value: 'unit_measure', input: false },
{ text: 'Net Price', value: 'net_price', input: false },
],
};
},
mounted() {
const { id } = this.$route.params;
this.order_id = id;
},
methods: {
submit() {
if (this.valid) {
API.updateOrder(this.order_id, this.data).then((result) => {
console.log(result);
this.$router.push({
name: 'Orders',
});
});
}
},
clear() {
this.$refs.form.reset();
},
},
};
</script>
Hopefully this will help someone else who can't see the forest for the trees...
When I declared the data() { ... } properties in the parent form I initialised orderdet as {} instead of [].

data-bind not working in List View template within Grid detail template

I need help using a Kendo UI list view which lives within a grid row detail template.
here is something I have done so far.
<div id="grid">
</div>
<script type="text/x-kendo-template" id="gridDetailTemplate">
<div class='grid-edit'>
<div class='edit-list'></div>
</div>
</script>
<script type="text/x-kendo-template" id="editItemtemplate">
<div class='edit-Item'>
#if(Type=='string'){#
<ul><li><b>#:Name#</b></li><li><input class='inputString' value='#:DataVal()#'/></li></ul>
#}else if(Type=='number'){#
<ul><li><b>#:Name#</b></li><li><input class='inputNumber' data-role='numerictextbox' data-type='number' value='#:DataVal()#'/></li></ul>
#}else if(Type=='date'){#
<ul><li><b>#:Name#</b></li><li><input class='inputDate' data-role='datepicker' value='#:kendo.toString(DataVal(),'MM/dd/yyyy')#'/></li></ul>
#}else if(Type=='boolean'){Name #<input type='checkbox'/>
#}#
</div>
</script>
<script type="text/javascript">
$(document).ready(function () {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var selFields = new Object();
$.each(data, function (index, elem) {
selFields[elem.Name] = new Object();
selFields[elem.Name]["type"] = elem.Type;
});
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: { url: "http://localhost:4916/Deal",
dataType: "json"
}
},
schema: {
data: "Data", total: "Total",
model: {
fields: selFields
}
}
},
height: 430,
filterable: true,
sortable: true,
pageable: false,
detailTemplate: kendo.template($("#gridDetailTemplate").html()),
detailInit: detailInit,
columns: [{
field: "SecurityName",
title: "Security Name",
width: 250
},
{
field: "DateOfAcquisition",
title: "Date Of Acquisition",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "Acres",
title: "Acres",
width: 120
}
]
});
});
});
function detailInit(e) {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var detailRow = e.detailRow;
detailRow.find(".edit-list").kendoListView({
dataSource: {
data: data,
schema: {
model: {
DataVal: function () {
switch (this.get("Type")) {
case "number"
}
if (e.data[this.get("Name")])
return e.data[this.get("Name")];
else
return '';
}
}
}
},
template: kendo.template($("#editItemtemplate").html())
});
});
}
</script>
My code gets dynamic field list and binds it to the data source for grid.
Then, in the detailInit event, I find the div within row detail and convert it into kendo UI list, for which the template have been created.
Now, when I use data-bind="value: DataVal()" ,it doesn't pick up the values of List data source. It works the way I have done i.e. value="#: DataVal() #". But, data-role does not convert the fields to specified types which are datepicker and numericinput in my case.
I believe that data-role not being used is caused due to same issue as data-bind not being read.
Can anyone help me out with this? Also, feel free to suggest any alternate ways and general code improvements. I am an ASP.NET developer and usually don't work on pure html and javascript.
PS: I would be happy to provide the context on what I am trying to achieve here if anyone is interested.
Thanks in advance.
If you can rig up a jsFiddle or jsBin example that would help debug the issue.
However, try removing the parenthesis:
data-bind="value: DataVal"
Kendo should detect that DataVal is a function and call it on its own.
I experienced a similar situation in a listview template. I created a JSFiddle to demonstrate:
http://jsfiddle.net/zacharydl/7L3SL/
Oddly, the solution is to wrap the contents of the template in a div. It looks like your template already has this, so YMMV.
<div id="example">
<div data-role="listview" data-template="template" data-bind="source: array"></div>
</div>
<script type="text/x-kendo-template" id="template">
<!--<div>-->
<div>method 1: #:field#</div>
<div>method 2: <span data-bind="text: field"></span></div>
<input data-role="datepicker" />
<!--</div>-->
</script>
var model = kendo.observable({
array: [
{ field: 'A'},
{ field: 'B'}
]
});
kendo.bind($('#example'), model);

Vuetify data-table, how to apply external filters?

How, if at all possible, to apply a filter to a Vuetify v-data-table, in conjunction with the 'regular' search property?
Following the Vuetify example (https://vuetifyjs.com/en/components/data-tables)
, consider a Vuetify data-table with two columns:
Dessert
Category
I want to control the table with a search box, linked to the "Dessert" column:
<v-data-table
:headers="headers"
:items="desserts"
:search="search"
></v-data-table>
and:
headers: [
{ text: 'Dessert (100g serving)', value: 'name' },
{ text: 'Category', value: 'category' },
],
But I want to control a filter on the Category column with a group of checkboxes (exact match). There is such a thing as a "custom-filter", but the documentation is not very detailed on that.
This looks to be the same question (unanswered): How to add individual filters for data-table in vuetify?
Turns out it's actually quite simple! The filters are defined in the headers property.
No changes required to the html element:
<v-data-table
:headers="headers"
:items="desserts"
:search="search"
></v-data-table>
The headers are moved to the computed-section and defined like this:
computed: {
headers() {
return [ { text: 'Dessert (100g serving)', value:'name' }
, { text: 'Category', value: 'category', filter: value => {
return this.array_of_matches.indexOf(value) !== -1
},
}
]
}
Where array_of_matches is a variable containing a list of search items. You may optionally want to add case conversion stuff like this: value.toString().toLocaleUpperCase()
The 'regular' search won't match anything on a header that has such a filter defined.

Resources