30
votes

I have a simple data table using Vuetify data table. One of the column is a createdOn (date time), I want to format it. How can I do it ?

This is what i get now:

This is what i get now

<template>
   <v-layout>
      <v-data-table :headers="headers" :items="logs">
      </v-data-table>
   <v-layout>
</template>
<script>
      headers: [
        { text: "Time", value: "createdOn", dataType: "Date" },
        { text: "Event Source", value: "eventSourceName" },
        { text: "Event Details", value: "eventDetails" },
        { text: "User", value: "user" }
      ],
      items: [],
</script>
4
how do you want to format it?Boussadjra Brahim
hi @Boussadjra Brahim I get "2019-09-14T17:03:24.3949548" format now. I want to make it "2019-09-14 3:24 AM". Is there a way to do it like pipes in angular?Kavin404

4 Answers

60
votes

You should use a custom row cell :

<v-data-table :headers="headers" :items="logs">
  <template v-slot:item.createdOn="{ item }">
    <span>{{ new Date(item.createdOn).toLocaleString() }}</span>
  </template>
</v-data-table>
8
votes

I found out a way to format cell values using dynamic slot names and a function in the header object:

In the <v-data-table> I did:

<template v-for="header in headers.filter((header) => header.hasOwnProperty('formatter'))" v-slot:[`item.${header.value}`]="{ header, value }">
    {{ header.formatter(value) }}
</template>

and in the vue data property I did:

headers: [
    ...
    { text: 'Value for example', value: '10000', formatter: formatCurrency },
    ...
]

And finally in the methods prop I did:

formatCurrency (value) {
    return '$' + value / 100
},

Here's a sandbox to see it in action: https://codesandbox.io/s/vuetify-datatable-value-formatter-jdtxj

EDIT: In this specific case you could use momentjs or javascript's Date()

0
votes

I have also used global filter with v-slot:

<v-data-table :headers="headers" :items="logs">
  <template v-slot:item.createdOn="{ item }">
    <span>{{ item.createdOn | myGlobalDateFilter }}</span>
  </template>
</v-data-table>
0
votes

In datatable component Datatable.vue

<template v-for="slot in slots" v-slot:[`item.${slot.slotName}`]="{ item }">
  <slot :name="slot.slotName" :variable="item"></slot>
</template>

export default {
props:
slots:{
  type:Array,
  default:null
},

and parent component

<Datatable
 :headers="headers"
  :items="stokhareketleri"
  :title="title"
  :slots="slots">
<template v-slot:column_name="{ variable }">
  <v-chip
        color="green"
        dark
      >
      {{variable.column_name}}
      </v-chip>
</template>
  </Datatable>


data () {
      return {
        slots:[{ 
          Id: 1, slotName: 'column_name'
          }],