[英]Vue JS V-For component reactivity
I have an issue where I can't get a child component to update when new data is passed to it.我有一个问题,当新数据传递给它时,我无法更新子组件。 The data is passing OK but the component doesn't update.
数据通过正常,但组件没有更新。
If I change the :key to the object rather than a unique ID it works!如果我将 :key 更改为对象而不是唯一的 ID,它就可以工作! But I get a warning error not to use the object as the key, so obviously that is not the way to go?!
但是我收到一个警告错误,不要使用对象作为键,所以显然这不是要走的路吗?!
<swiper ref="timelineCarousel" :options="swiperOption">
<div slot="pagination" class="swiper-pagination kt-margin-b-10"></div>
<!-- creates swiper slides for each timeline -->
<swiper-slide
v-for="timeline in timelines"
:key="timeline.id + timeline.time"
class="col-md-3 noSwipe"
>
<!-- creates the timeline draggable elements -->
<timeline
:id="timeline.id"
:key="timeline.id + timeline.current_vehicle_reg"
:hour-to-scroll-to="scrollHour"
:day-to-scroll-to="scrollDay"
:month-to-scroll-to="scrollMonth"
:year-to-scroll-to="scrollYear"
></timeline>
</swiper-slide>
</swiper>
So when I update this.timeline I can see the data changing in the vue toolsnbut the component doesn't update - unless I use the timeline object as the key!!因此,当我更新 this.timeline 时,我可以在 vue 工具中看到数据发生变化,但组件不会更新 - 除非我使用时间线对象作为键!
I should add that I have added a watcher on the timelines object and that is triggered when I update the data using:我应该补充一点,我在时间线对象上添加了一个观察者,当我使用以下方法更新数据时会触发该观察者:
Vue.set(this.timelines, 0, event);
I have no idea what I am doing wrong.我不知道我做错了什么。
The key is simply a way to give a unique identifier to the list of elements.键只是一种为元素列表提供唯一标识符的方法。 If you want to make sure that modifying your list of timelines gets the result you expect, it must have a unique key that is not the index of the array.
如果你想确保修改你的时间线列表得到你期望的结果,它必须有一个唯一的键,而不是数组的索引。
// bad
<swiper-slide
v-for="(timeline, index) in timelines"
:key="index"
class="col-md-3 noSwipe"
>
Most often, the object's ID can be used for the key.大多数情况下,对象的 ID 可用作键。 You don't want to use a complex data structure like an object for an ID.
您不想使用复杂的数据结构,例如 ID 的对象。
// good
<swiper-slide
v-for="timeline in timelines"
:key="timeline.id"
class="col-md-3 noSwipe"
>
The Vue.js documentation is very good and I recommend reading it yourself. Vue.js 文档非常好,我建议您自己阅读。 Here is a link to using keys with the
v-for
directive.这是使用带有
v-for
指令的键的链接。
You don't need the :key
property on the children nested inside to fix this issue, just on the element with the v-for
.您不需要
:key
嵌套在里面的子元素上的属性来解决这个问题,只需在带有v-for
的元素上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.