If you want to loop over a range in your Vue template, it's not too complicated.
I'll show you how!
Well, the v-for
directive in Vue let's us loop over an array. But it also let's us loop over a range:
<template><ul><li v-for="n in 5">Item #{{ n }}</li></ul></template>
This will render out:
When we use v-for
with a range, it will start at 1 and end on the number we specify.
There are probably times when you'd like to start at a number other than 1.
While Vue doesn't give us this directly, we can use a little trick to get around that:
<template><ul><li v-for="n in 5">Item #{{ n + offset }}</li></ul></template>
We simply add an offset
to our loop!
For example, if the value of our offset
is 4
, this would now render:
We can use this to render out only part of a list:
<template><ul><li v-for="n in 3">{{ fruit[n - 1] }}</li></ul></template>
export default {data() {return {fruit: ['Apples', 'Oranges', 'Bananas', 'Pineapple'],};}}
We have to subtract 1 so that we start at 0
instead of at 1
.
This will render out:
But even though you can do this, it's probably not the best way to limit a list.
The best approach would be using a computed prop:
<template><ul><li v-for="fruit in filteredFruit">{{ fruit }}</li></ul></template>
export default {data() {return {fruit: ['Apples', 'Oranges', 'Bananas', 'Pineapple'],};},computed: {filteredFruit() {return this.fruit.slice(0, 3);}}}
This will result in only the first 3 fruit being rendered.
But because we're using a computed prop, it will only have to compute it once. This is more efficient than the previous method, which would compute it on every single render.
Computed props are one of the most important concepts in Vue. You should be using them everywhere.
I mean it. Use them everywhere that you can.
If you want to dive deeper into v-for
, I built a recursive component that replicates the functionality. The article goes deep into recursion, nested slots, and nested scoped slots. It's a lot of fun!