Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a Component in Vue - Custom elements in iteration require 'v-bind:key' directives

Tags:

vue.js

I'm attempting to create multiple custom components (just as a proof of concept so nothing fancy just duplicating the same component 5 times) but I'm getting the following error:

Custom elements in iteration require 'v-bind:key' directives.

Here's the code for the loop (which I'm pretty sure where the problem is:

<template>
    <div>
        <app-server-status v-for="server in 5"></app-server-status>
    </div>
</template>

<script>
    import ServerStatus from './ServerStatus'

    export default {
        components: {
            'app-server-status': ServerStatus
        }
    }
</script>

Now from the reading up I've done I can see that I need a key somewhere due to the limitations of using a component in later versions of Vue - just not quite sure on the correct way to do it. Can some one advise me how I'd need to modify that specific example to just show the component 5 times?

Side note: The code below gives me the result I need in the app but VSCode is still giving me an error (Expected 'v-bind:key' directive to use the variables which are defined by the 'v-for' directive.):

<app-server-status v-for="server in 5" :key="index"></app-server-status>
like image 631
Web Develop Wolf Avatar asked Sep 05 '25 03:09

Web Develop Wolf


1 Answers

I've fixed the same error by adding the :key attribute to the element.

<app-server-status v-for="server in 5" :key="server"></app-server-status>

It's working fine for me. The duplicating same component displaying 5 times. Hope, It will be helpful to you.

I've got this solution from the https://github.com/vuejs/vetur/issues/858

like image 150
Sathish Chelladurai Avatar answered Sep 07 '25 21:09

Sathish Chelladurai