Diabelna Pomidorowa
Diabelna Pomidorowa

Reputation: 83

Vue table field formatting

I am trying to format date from unix timestamp to human friendly date, but I got stuck. I would like it to work in this way:

<Column field="createdAt" header="Created at">{{ new Date(this).toLocaleString() }}</Column>

but I do not know how could I refer to that field particular cell. Someone can help? Here is the rest of my code:

<template>
  <div>
    <DataTable :value="filters">
      <Column field="id" header="Id"></Column>
      <Column field="highlight" header="Highlight"></Column>
      <Column field="usage" header="Usage"></Column>
      <Column field="createdAt" header="Created at">{{ new Date(this.$data.createdAt).toLocaleString() }}</Column>
    </DataTable>
  </div>
</template>

<script lang="ts">
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import { ref, defineComponent } from 'vue'
import { DynamicFilterRowDto } from "@/api/api";
import { getDynamicFilters } from "@/service/data";

export default defineComponent({
  name: 'DynamicFilters',
  components: {
    DataTable,
    Column,
  },
  setup: () => {
    const filters = ref<DynamicFilterRowDto[] | undefined>()

    const fetch = async () => {
      filters.value = await getDynamicFilters()
    }
    fetch()
    return { filters, formatOptions: { format: "MM-dd-yyyy", type: "date" }  }
  },

})
</script>

Upvotes: 0

Views: 2845

Answers (2)

Leonardo Oliveira
Leonardo Oliveira

Reputation: 1

In Vue 3+ you can still do it like tony19 did:

<Column field="createdAt" header="Created at">
  <template #body="slotProps">{{ new Date(slotProps.data.createdAt).toLocaleString() }}</template>
</Column>

Upvotes: 0

tony19
tony19

Reputation: 138216

The <Column> component has a body slot, whose data slot prop provides the row data corresponding to the array element in filters[]. You could therefore use data to access createdAt:

<Column field="createdAt" header="Created at">
  <template #body="{ data }">{{ new Date(data.createdAt).toLocaleString() }}</template>
</Column>

demo

Upvotes: 4

Related Questions