如何将数据从 Laravel 传递到 Vue.js 组件 v-for

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

如何将数据从 Laravel 传递到 Vue.js 组件 v-for ?

我试过下面的代码:

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

但是 returns:

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

您不在绑定中使用花括号语法。

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

events 数组需要在你的虚拟机的数据函数中定义:

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

如果您想在页面加载时异步获取事件数据,请将 ajax 调用放在虚拟机的 created() 挂钩中:

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

要解决 Vue 向您显示的警告消息,请添加 :key="event.id"(如果您的事件有 id 属性,否则任何其他唯一 属性):

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

错误消息明确指出您应该使用 :key 绑定:

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>

来自资源: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.