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