Search code examples
cssvuejs3vuetifyjs3

How can I truncate v-data-table column content by using cellProps?


I created following data table:

<script setup lang="ts">
const headers: any = [
  {
    title: 'Title',
    key: 'title',
    cellProps: {
      class: ['my-bold-class']
    }
  }
  ...
]

const items = [...]
</script>

<template>
  <v-data-table
    :headers
    :items
  ></v-data-table>
</template>

Now I want to truncate the title column content if it exceeds 200px, therefore I did this:

const headers: any = [
  {
    title: 'Title',
    key: 'title',
    cellProps: {
      class: ['my-bold-class', 'text-truncate']
    },
    width: '200' // I'd have used maxWidth instead, but it doesn't seem to work
  }
  ...
]

Based on the documentation, text-truncate only works on display: block or display: inline-block items, therefore I did this:

cellProps: {
  class: ['my-bold-class', 'text-truncate', 'd-block']
}

And this is the result: enter image description here

As you can see the title column is no more vertically centered. How can I fix it?

P.S. I also noticed that headers can also have a nowrap attribute, like this:

const headers = [
  {
    ...
    nowrap: true
  }
]

but I don't really know how to use it.


Solution

  • I found a solution which doesn't require passing any styles/classes at all, only Vuetify's power. It's possible to pass to each header item nowrap: true and a max width (I don't know why it doesn't work with width), like this:

    const headers: any = [
      {
        title: 'Title',
        key: 'title',
        cellProps: {
          class: 'my-bold-class'
        },
        maxWidth: '430',
        nowrap: true
      }
      ...
    ]
    

    If the title exceeds 430px it will be truncated and ellipsis will be shown (you can see it in action here).