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

问题描述 投票:0回答:2

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

我试过下面的代码:

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

但它返回:

使用v-for呈现的组件列表应具有显式键。

laravel vue.js v-for
2个回答
1
投票

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

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

需要在vm的数据函数中定义events数组:

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

如果要在页面加载时异步获取事件数据,请将ajax调用放在vm的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" />

0
投票

错误消息清楚地表明您应该使用:key绑定:

使用v-for呈现的组件列表应具有显式键。

    <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

将v-for与组件一起使用时,现在需要一个密钥。升级时,您可能会看到一堆“软警告”,但这不会影响应用程序的当前行为。

© www.soinside.com 2019 - 2024. All rights reserved.