繁体   English   中英

Vue JS V-For 组件反应性

[英]Vue JS V-For component reactivity

我有一个问题,当新数据传递给它时,我无法更新子组件。 数据通过正常,但组件没有更新。

如果我将 :key 更改为对象而不是唯一的 ID,它就可以工作! 但是我收到一个警告错误,不要使用对象作为键,所以显然这不是要走的路吗?!

 <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>

因此,当我更新 this.timeline 时,我可以在 vue 工具中看到数据发生变化,但组件不会更新 - 除非我使用时间线对象作为键!

我应该补充一点,我在时间线对象上添加了一个观察者,当我使用以下方法更新数据时会触发该观察者:

Vue.set(this.timelines, 0, event);

我不知道我做错了什么。

键只是一种为元素列表提供唯一标识符的方法。 如果你想确保修改你的时间线列表得到你期望的结果,它必须有一个唯一的键,而不是数组的索引。

// bad
<swiper-slide
  v-for="(timeline, index) in timelines"
  :key="index"
  class="col-md-3 noSwipe"
>

大多数情况下,对象的 ID 可用作键。 您不想使用复杂的数据结构,例如 ID 的对象。

// good
<swiper-slide
  v-for="timeline in timelines"
  :key="timeline.id"
  class="col-md-3 noSwipe"
>

Vue.js 文档非常好,我建议您自己阅读。 这是使用带有v-for指令的键的链接。

您不需要:key嵌套在里面的子元素上的属性来解决这个问题,只需在带有v-for的元素上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM