0

How to pass data from Laravel to Vue.js component v-for ?

I have tried the code below:

<my-component
    v-for="(event, eventIndex) in {{ $data['events'] }}">
</my-component>

But it returns:

component lists rendered with v-for should have explicit keys.

1
  • you sure you want to have multiple my-component or you want a v-for inside this component ? Commented Mar 1, 2018 at 16:06

2 Answers 2

1

You don't use curly braces syntax in bindings.

<my-component v-for="(event, eventIndex) in events" />

events array needs to be defined in your vm's data function:

data() {
  return {
    events: [] // initialize as an empty array if you fetch the data async
  }
}

If you want to fetch your event data asynchronously when the page loads, put the ajax call inside the created() hook of your vm:

created() {
  $.ajax({ method: 'get', url: 'your/api/to/get/events' })
    then((response)=> {this.events = response.data})
}

To solve the warning message Vue is showing you, add a :key="event.id" (if your events have an id property, otherwise any other unique property):

<my-component v-for="(event, eventIndex) in events" :key="event.id" />
Sign up to request clarification or add additional context in comments.

Comments

0

The error message clearly says that you should use :key binding:

component lists rendered with v-for should have explicit keys.

    <my-component
        v-for="(event, eventIndex) in {{ $data['events'] }}" :key="eventIndex">
         <!-- You can bind key to unique key, :key="event.id" -->
         <!-- However, it's perfectly good to use :key="eventIndex" -->
    </my-component>

From a resource: v2.2.0 release

When using v-for with a component, a key is now required. You will likely see a bunch of "soft warnings" when you upgrade, but this does not affect the current behavior of your app.

6 Comments

Adding the eventIndex as a key makes no sense other than getting rid of the warning.
The Vue message says "should", not "needs to".
@connexo while using v-for inside a component you must provide a :key
Why not read the docs you're linking? You don't have to. It is recommended to provide a key with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.
When you use v-for inside a div you can omit :key but it's a required while using component. I have read somewhere, trying to find the source.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.