Bogdan Balan Bogdan Balan - 9 days ago 6
Javascript Question

Vue.js - repeat an element a specific number of times

I would like to use Vue.js to repeat an element n times, based on the

num-labels
prop.

<label-parent num-labels="4"></label-parent>


This is my component:

<template>
<div id="label-parent">
<div v-for="idx in numLabels">
{{idx}}
</div>
</div>
</template>

<script>;
export default {
name: "LabelParent",
props: ['numLabels'],
}
</script>


This code only outputs an empty div:
<div id="label-parent"></div>
. What is the correct way of doing this?

d3l d3l
Answer
<label-parent num-labels="4"></label-parent>

Passes 4 as a string which won't work with v-for.

Pass your argument with : to evaluate the expression so you get an actual number which will work with v-for.

<label-parent :num-labels="4"></label-parent>

BTW:

I highly suggest typing your props.

You can type your props like this:

export default {
    props: {
        numLabels: {
            type: Number, // type of the property
            required: (true|false), // is this prop required or not?
            default: 0 // default value for this prop
        }
    }
}

See Prop Validation