Search code examples
vue.jsnuxt.jsv-for

I'm looping through my array with v-for and I would like that each item goes to a specific grid position. How do I do that?


Well, I have this component and I want to display my data in a grid that looks like this:

enter image description here

I'm looping through my last 3 items of my array

async created(){
        const res = await axios.get("https://base-url/posts")
        const data = res.data;
        this.destaques= data.slice(-3);     
    }

But when I use v-for I do not see a way to put them in the positions above.

<div v-for="(destaque, i) in destaques" :key='i'>
    <nuxt-link :to="`/${destaque.id}`">
         <p>{{destaque.title}}</p>
    </nuxt-link>
</div>

I've tried this way

        <div class="destaques__principal">
            <nuxt-link tag="a" :to='`/${destaques[0].id}`' class="wrap-link">
            <img :src="`${destaques[0].image[0].name}`" alt="">
            <div class="white-box">
                <h1 class="white-box__title">{{destaques[0].title}}</h1>
            </div>
            </nuxt-link>
            </div>
        <div class="destaques__cima">
            <nuxt-link tag="a" :to='`/${destaques[1].id}`' class="wrap-link">
            <img :src="`${destaques[1].image[0].name}`" alt="">
            <div class="white-box">
                <h1 class="white-box__title">{{destaques[1].title}}</h1>
            </div>
            </nuxt-link>

        </div>
        <div class="destaques__baixo">
            <nuxt-link tag="a" :to='`/${destaques[2].id}`' class="wrap-link">
            <img :src="`${destaques[2].image[0].name}`" alt="">
            <div class="white-box">
                <h1 class="white-box__title">{{destaques[2].title}}</h1>
            </div>
            </nuxt-link>

        </div>

and first it works but when I click on the logo to get back to home page, it gives me an error. I don't get that error when I display the data like this destaque.title. So I was wondering if there is a way to dynamically arrange the items to specific positions on the grid. Is there anyone that could help me out, please?


Solution

  • You could use CSS grid to achieve this. DEMO: https://jsfiddle.net/kpset24g/1/

    HTML

    <div class="grid">
        <div v-for="(item, i) in items" class="box" :class="{'full-height-box': i == 0}">
            {{item}}
        </div>
    </div>
    

    CSS

    .grid {
      display: grid;
      grid-template-columns: 50% 50%;
      grid-template-rows: 2;
      grid-gap: 10px; /* OPTIONAL */
    }
    
    .full-height-box {
      grid-row: 1 / span 2;
    }
    
    .box { /* Custom styles of your box */ }
    

    JS (Just as demo)

    new Vue({
      //...
      data: {
        items: ['Block 1', 'Block 2', 'Block 3']
      }
    })