Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break v-for loop in vue.js?

I have this v-for loop an my vue.js app:

  <div v-for="(word, index) in dictionary"> 
     // break if index > 20
     <p>{{word}}</p>
  </div>

I want to break out of the loop after rendering 20 words. How can I achieve this? I looked at the docs but did not see anything about this.

like image 717
Karlom Avatar asked Aug 01 '17 05:08

Karlom


Video Answer


3 Answers

you can manipulate the array before loop start

<div v-for="(word, index) in dictionary.slice(0,20)"> 
    <p>{{word}}</p>
</div>
like image 124
cwang Avatar answered Oct 21 '22 17:10

cwang


You have to create a computed value for your truncated dictionary (e.g. it is better to prepare data for rendering):

computed: {
 shortDictionary () {
   return dictionary.slice(0, 20)
 }
}

...

<div v-for="(word, index) in shortDictionary"> 
   <p>{{word}}</p>
</div>
like image 20
euvl Avatar answered Oct 21 '22 15:10

euvl


For this scenario, this solution works best for me.

<div v-for="(word, index) in dictionary" v-if="index <= 20"> 
    <p>{{word}}</p>
</div>
like image 5
maswahyu Avatar answered Oct 21 '22 15:10

maswahyu