Search code examples
vue.jsgridviewlayoutvuetify.js

Vuetify adaptative grid layout from item list


I have what seems to be a very common issue, but I can get over it.

I have an API query that returns me a list of object.

I want to display it my page as a grid of card filled with the content.

I want my grid to be in 5 column, and the number of row will adapt to the number of element in my list.

I can figure out how to achieve it.

For example: i have a query returning

items[
   {"id":1,"title":"title1,"description":"description1"}
   {"id":2,"title":"title2,"description":"description2"}
   {"id":3,"title":"title3,"description":"description3"}
   {"id":4,"title":"title4,"description":"description4"}
   {"id":5,"title":"title5,"description":"description5"}
   {"id":6,"title":"title6,"description":"description6"}
   {"id":7,"title":"title7,"description":"description7"}
]

My grid as to be made from 7 elements with systematically 5 columns and adaptive rows like:

enter image description here

And if my query returns for example 14 elements, the layout should adapt to look like this:

enter image description here

The closest I was able to get with the code was.

<v-container class="mt-2">
      <h1>Top Rated views</h1>
      <v-row v-for="n in gridDivider" :key="n" class="n === 1 ? 'mb-6' : ''">
        <v-col v-for="(item,index) in Items" :key="index">
          <v-card class="mx-auto" max-width="300">
            <v-img
              class="white--text align-end"
              height="200px"
              src="item.avatar"
            >
              <v-card-title>anything as text</v-card-title>
            </v-img>

            <v-card-subtitle class="pb-0"> Number 10 </v-card-subtitle>

            <v-card-text class="text--primary">
              <div>Whitehaven Beach</div>

              <div>Whitsunday Island, Whitsunday Islands</div>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>
    </v-container>

Thanks for helping


Solution

  • It could be done if you change v-row and v-col declarations this way:

    <v-row class="five-cols">
      <v-col v-for="(item,index) in Items" :key="index">
    ...
    

    and create a CSS class five-cols using CSS Grid Layouts:

    .five-cols {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
    }
    

    Example at CodePen