首页 > 解决方案 > VueJs + BootstrapVue:表格删除项目仅在第一页

问题描述

我创建了一个页面,在其中列出了 BootstrapVue b 表中的所有项目。对于每个项目,我添加了删除该项目的可能性。

当我使用 b-pagination 元素和 :per-page 属性激活分页时,页面上出现了意外行为。问题是它只适用于第一页,但所有其他页面都获取第一页的数据。例如,如果项目总数为 10 并且我每页显示 5 个项目,则显示接下来 5 个项目的第二页仍将尝试删除第一页项目。

<b-table
  id="traffic-routes"
  :fields="fieldsForTrafficRoutes"
  :items="itemsForTrafficRoutes"
  :per-page="perPageForTrafficRoutes"
  :current-page="currentPageForTrafficRoutes"
>
    <template v-slot:cell(action)="data">
      <div class="d-flex align-items-center justify-content-end">
        <a class="action-icon mr-2"
          @click="removeRow(data.index)"
        > Delete </a>
     </div>
   </template>  

</b-table>

<b-pagination
  v-model="currentPageForTrafficRoutes"
  aria-controls="traffic-routes"
  align="right"
  :total-rows="
  itemsForTrafficRoutes ? itemsForTrafficRoutes.length : 0"
  :per-page="perPageForTrafficRoutes"
></b-pagination>

export default {
  data() {
    return {
      perPageForTrafficRoutes: 5,
      currentPageForTrafficRoutes: 1,
      // ...
    }
  },
  computed: {
    ...mapGetters([
      'getAllTrafficRoutes',
    ]),
    itemsForTrafficRoutes() {
      return JSON.parse(JSON.stringify(this.getAllTrafficRoutes));
    },
  }
}

但是,我试图使项目动态:

itemsForTrafficRoutes() {
  const foo = JSON.parse(JSON.stringify(this.getAllTrafficRoutes));
  return foo.slice((this.currentPageForTrafficRoutes - 1) *
    this.perPageForTrafficRoutes, this.currentPageForTrafficRoutes * this.perPageForTrafficRoutes
  );
},

这将使每个页面的项目都是唯一的,它只会在第一页包含前 5 个,然后在下一页更新到接下来的 5 个项目,但是,表格只显示第一页,即使在下一页也是空的虽然物品存在

标签: javascriptvue.jsbootstrap-4vuejs2bootstrap-vue

解决方案


那是因为您使用的是index来自作用域插槽的。索引将基于显示的行,而不是提供给items道具的数组中项目的实际索引。

这在Scoped field slot部分下的注释中的文档中进行了描述。

index并不总是实际行的索引号,因为它是在对原始表数据应用过滤、排序和分页后计算的。该index值将引用显示的行号。这个数字将与可选的 v-model 绑定变量中的索引对齐。

我建议要么使用对象中的唯一标识符(如果有的话),或者使用引用来删除它。


推荐阅读