如何将数据从Laravel传递到Vue.js组件v-for?
我尝试过以下代码:
<my-component
v-for="(event, eventIndex) in {{ $data['events'] }}">
</my-component>
但它返回:
使用v-for呈现的组件列表应具有显式键。
答案 0 :(得分:1)
您不会在绑定中使用花括号语法。
events
需要在vm的数据函数中定义 data() {
return {
events: [] // initialize as an empty array if you fetch the data async
}
}
数组:
created()
如果要在页面加载时异步获取事件数据,请将ajax调用放在vm的created() {
$.ajax({ method: 'get', url: 'your/api/to/get/events' })
then((response)=> {this.events = response.data})
}
挂钩中:
:key="event.id"
要解决Vue向您显示的警告消息,请添加id
(如果您的事件具有<my-component v-for="(event, eventIndex) in events" :key="event.id" />
属性,否则添加任何其他独特属性):
{{1}}
答案 1 :(得分: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与组件一起使用时,现在需要一个键。您可能会看到一堆&#34;软警告&#34;升级时,但这不会影响应用的当前行为。