How can I add a element everytime after 4 elements

2019-09-15 07:23发布

问题:

I'm immigrating my code to Vue.js so pretty new to Vue. As you see the screenshot(link below), There are 4 columns inside div with columns class name. I was trying to use v-if to add the div(class columns) conditionally but I have no idea how to get a length of columns elements in Vue.

Example Code

<template lang="pug">
.container
  .columns(v-if="") // add this conditionally
    .column.is-3.vid(v-for='item in items')
      .panel
        p.is-marginless
         a(href=item.videoId)
           img(src=item.thumbnail)
        .panel.vidInfo
          .columns.hax-text-centered
            .column
              .panel-item.reddit-ups
                | item.score
                i.fa.fa-reddit-alien.fa-2x
              .panel-item.reddit-date
                i.fa.fa-calendar.fa-2x
</template>

回答1:

You can access v-for iteration number like this:

change

 .column.is-3.vid(v-for='item in items')

to

.column.is-3.vid(v-for='(item, index) in items')

then somewhere where you need it check the index:

v-if="(index % 4 === 0) ? 'show it after every 4 elements' : ''"

for example, inject a span:

<span v-if="index % 4 === 0">after 4</span>