【问题标题】:Vue v-for list not re-rendering after computed data update计算数据更新后Vue v-for列表未重新渲染
【发布时间】:2018-11-29 09:40:39
【问题描述】:

我正在为大量卡片实现分页,我一次显示 10 张卡片,并希望通过单击两个按钮来显示下一个(或前 10 个)的 10 个。

我是这样做的:

export default {
  ...
  data() {
    return {          
      pois: [], // My list of elements
      pageNumber: 0, // Current page number
    };
  },
  props: {
    size: {
      type: Number,
      required: false,
      default: 10, // 10 cards per page
    },
  },
  computed: {
    pageCount() {
      // Counts the number of pages total
      const l = this.pois.length;
      const s = this.size;
      return Math.floor(l / s);
    },
    paginatedData() {
      // Returns the right cards based on the current page
      const start = this.pageNumber * this.size;
      const end = start + this.size;
      return this.pois.slice(start, end);
    },
  },
  methods: {
    nextPage() {
      this.pageNumber += 1;
    },
    prevPage() {
      this.pageNumber -= 1;
    },
  }
  ...
};

还有我的模板:

<div v-for="poi in paginatedData" :key="poi.id">                
  <card :poi="poi"/>
</div>

一切都应该正常工作(页面更改确实会在控制台中输出正确的卡片)但我的列表没有更新,即使每次点击都会调用计算方法。

是什么导致了这个问题?我读过它可能与缺少的 :key 值相关联,但它就在那里,并且没有直接和手动更新数组中的数据,只是被切掉了。

【问题讨论】:

  • 可以poi.id 在您的数组中的每个对象上具有相同的值吗?
  • 在这种情况下每个 ID 都是唯一的
  • 尝试使用索引键:&lt;div v-for="(poi, key) in paginatedData" :key="key"&gt;
  • @Christopher 您的代码有效 (proof of concept)。也许您的问题是关于如何获取数据 (pois)

标签: vue.js vuejs2


【解决方案1】:

首先,试试这个更改,确定一下,并在评论中告诉我它是否有效。

export default {
  ...
  computed: {
    paginatedData() {
      ...
      const end = start + this.size - 1;
      ...
    },
  ...
};

是的:尝试使用索引而不是 id:

<div v-for="(poi, idx) in paginatedData" :key="idx">                
  <card :poi="poi"/>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2018-09-11
    • 2020-12-16
    • 2021-12-12
    • 2022-01-23
    • 1970-01-01
    • 2023-01-10
    • 2021-05-15
    相关资源
    最近更新 更多