ddon
ddon

Reputation: 205

Same v-for loop in two different <div>

I want to put the same v-for loop in two different <div>. Is there a way to use a v-for loop only once?

Here is an example:

<div class="v-for-1">
  <div v-for="(item, index) in items" :key="index">
    blah blah
  </div>
</div>

<div class="v-for-2">
  <div v-for="(item, index) in items" :key="index">
    blah blah
  </div>
</div>

Upvotes: 0

Views: 1633

Answers (3)

Mossen
Mossen

Reputation: 604

You need to create a component and call it twice:

vFor.vue

<div :class="YOUR_CLASS_FROM_PROPS">
 <div v-for="(item, index) in ITEMS_FROM_PROPS" :key="index">
   blah blah
 </div>
</div>

and then:

<vFor :items="ITEMS" :className="vfor-1" />
<vFor :items="ITEMS" :className="vfor-2" />

OR

<div v-for="(_, i) in [0, 1]" :key="index" :class="v-for`${i}`">
 <div v-for="(item, index) in items" :key="index">
   blah blah
 </div>
</div>

Upvotes: 0

N. Djokic
N. Djokic

Reputation: 1046

I am not sure what exactly you want to achieve but you can do something like this if you want to print two divs in same loop:

    <div class="v-for-1">
      <div v-for="(item, index) in items" :key="index">
        <div> blah blah </div>
        <div> blah blah </div>
      </div>
    </div>

Upvotes: 1

Scornwell
Scornwell

Reputation: 605

You can just move the v-for to a container div and use it multiple times there. In the below example you will create 2 divs with access to the same item.

<div v-for="(item, index) in items" :key="index"
     class="parent-v-for">

  <div class="v-for-1">
    {{item}}
  </div>

  <div class="v-for-2">
    {{item}}
  </div>

</div>

Upvotes: 0

Related Questions