Search code examples
vuejs3vuetify.jsv-data-table

Line selector on v-datatables (Vuetify)


Can you help me?

I want to have the same result in vuejs3 , I use v-datatable and my problem is that I don’t know how to select a line with the v-datatable of Vuejs3

Thank you for your help

enter image description here


Solution

  • If you want to color it by position (i.e. first two rows should always be green, no matter the sorting), you can use CSS:

        .v-table > .v-table__wrapper > table > tbody > tr:nth-child(-n+2) td{
          background: #e1eed7;
        }
        .v-table > .v-table__wrapper > table > tbody > tr:nth-child(n+3):nth-child(-n+4) td{
          background: #fff1c7;
        }
        .v-table > .v-table__wrapper > table > tbody > tr:nth-child(n+5):nth-child(-n+6) td{
          background: #fce3d4;
        }
    

    const { createApp, ref } = Vue;
    const { createVuetify } = Vuetify
    const vuetify = createVuetify()
    const app = {
      setup(){
        const headers = [{key: 'id', title: 'ID'},{key: 'name', title: 'Name'}]
        const items = ref(Array.from({length:8}, (_,i) => ({
              id: 1 + i, 
              name: `Item ${1 + i}`
            })))
       
        return {
          headers,
          items,
        }
      }
    
    }
    createApp(app).use(vuetify).mount('#app')
    .v-data-table.colortable .v-table__wrapper > table > thead > tr th{
      background: #d7d7d7;
    }
    .v-table.colortable > .v-table__wrapper > table > tbody > tr:nth-child(-n+2) td{
      background: #e1eed7;
    }
    .v-table.colortable > .v-table__wrapper > table > tbody > tr:nth-child(n+3):nth-child(-n+4) td{
      background: #fff1c7;
    }
    .v-table.colortable > .v-table__wrapper > table > tbody > tr:nth-child(n+5):nth-child(-n+6) td{
      background: #fce3d4;
    }
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" />
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify-labs.min.css" />
    <link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
    <div id="app">
      <v-app>
        <v-main>
          <v-data-table
            class="colortable"
            :headers="headers"
            :items="items"
            item-title="name"
            item-value="id"
          ></v-data-table>
        </v-main>
      </v-app>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify-labs.js"></script>

    In Vuetify 2, you could set a row class through the associated item, but this is not supported by the current version of VDataTable (Vuetify 3.1.13).