Search code examples
javascriptvue.jsvuejs2vue-componentv-for

Create a number of components


I would like to know if with sight, it was possible to call a component a certain number of times?

Basically I have a size variable that is initialized to 5 and I would like it to be 5 times the widget component.

This is my current code:

Template :

<template>
    <div v-for="item in size" :key="item">
        <Widget/>
    </div>
</template>

Script :

import Widget from './Widget'
export default {
    data () {
        return {
            size: 5
        }
    },
    components: {
        Widget
    }
}

I've looked with v-for but I don't understand how it works.


Solution

  • A component is allowed to have only one root element, so v-for on the outermost element throws an error because it would create multiple root elements. Either of these should solve it for you:

    <template>
        <div>
            <div v-for="item in size" :key="item">
                <Widget/>
            </div>
        </div>
    </template>
    

    OR

    <template>
        <div>
            <Widget v-for="item in size" :key="item" />
        </div>
    </template>