Reputation: 14834
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.
Upvotes: 11
Views: 38415
Reputation: 4765
You can use Array.slice
and Math.min
functions:
<div v-for="(word, i) in dictionary.slice(0, Math.min(20, dictionary.length))">
<p>{{word}}</p>
</div>
Using computed methods:
computed: {
firtsElements () {
return this.dictionary.slice(0, Math.min(20, this.dictionary.length))
}
}
Upvotes: 0
Reputation: 3642
With the ability to use v-for with a range, here is a solution that does not involve creating a new array via splice or using a computed:
<div v-for="i in Math.min(dictionary.length, 20)">
<p>{{dictionary[i-1]}}</p>
</div>
https://v2.vuejs.org/v2/guide/list.html
Upvotes: 0
Reputation: 125
For this scenario, this solution works best for me.
<div v-for="(word, index) in dictionary" v-if="index <= 20">
<p>{{word}}</p>
</div>
Upvotes: 5
Reputation: 56
To do this at the v-for level, create a data object with the limit and compare it to index to control v-for with v-if.
<div v-for="(word, index) in dictionary" v-if="index<=limit">
// break if index > 20
<p>{{word}}</p>
</div>
<script>
export default{
data(){
return{
limit: 20 }
}
}
</script>
Upvotes: 0
Reputation: 4786
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>
Upvotes: 5
Reputation: 1104
you can manipulate the array before loop start
<div v-for="(word, index) in dictionary.slice(0,20)">
<p>{{word}}</p>
</div>
Upvotes: 32