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?
Add key to Vue v-for loops. A common Vue best practice is to use :key in your v-for loops. key is a special attribute that lets us give hints for Vue's rendering system to identify specific virtual nodes. If we don't provide a unique key , Vue will try to minimize element movement when updating the DOM.
v-for directive is a Vue. js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let's apply the v-for directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value.
Vue components, on the other hand, are great when you want to reuse template code, aka child component, that can be used in multiple parent components.
v-for
can also take an integer. In this case it will repeat the template that many times.
<div v-for="n in 4">{{n}}</div>
and you will need to use v-bind:num-labels="4"
to parse the value as number
.
Vue Docs
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With