Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
bbalan Avatar asked Dec 01 '16 20:12

bbalan


People also ask

How do you use a loop in VUE component?

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.

What is V-for in Vue?

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.

Does Vue reuse components?

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.


2 Answers

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

like image 131
ABDEL-RHMAN Avatar answered Sep 30 '22 13:09

ABDEL-RHMAN


<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

like image 22
marco-a Avatar answered Sep 30 '22 15:09

marco-a