Search code examples
laravelvue.jsv-for

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


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.


Solution

  • 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" />