首页 > 解决方案 > 在 vue/nuxt 中获取和渲染大型数据集时性能下降

问题描述

好的,我的情况如下......我必须根据axios获取的项目在vue中渲染一个列表。每个项目都有一个 ID、一个代码(字符串)和一个描述,我在系统的数据库(mysql)中有14.000多个这些项目。此外,这些项目分为119 个类别,这些类别也有代码和描述(某些类别的项目比其他类别多)。我的工作是以一种方式显示这些类别的列表,每次有人点击一个类别时,它就会折叠以显示该类别的项目列表。

我当前的解决方案:每次有人点击一个类别时,系统都会发出 axios get 请求来获取该类别的项目(它返回一个对象数组),然后我使用v-for渲染它们。为了获取正确的项目,我使用 knex(nodejs 后端)构建了一个特定的查询。问题是当我点击一个有很多项目的类别时,或者如果我点击很多类别有点快,网站会变得非常慢,有时它会完全停止。所以我想知道在 vue 中渲染长列表的正确和优化方式是什么。

我的 axios 请求代码:

getCategoryItems(index) {
  this.isOpen = index
  this.loading()
  const cat = this.categories[index].code

  this.$axios
    .get('/api/items', {
      params: {
        category: cat
      }
    })
    .then(response => {
      this.categoryItems = response.data
    })
    .catch(error => {
      console.log(error)
    })
}

我用于渲染列表的代码(我正在使用 buefy):

<section ref="modalContent" class="modal-card-body">
    <b-collapse
      v-for="(category, index) of categories"
      :key="index"
      :open="isOpen == index"
      @open="getCategoryItems(index)"
      class="card"
      animation="slide"
    >
      <template #trigger="props">
        <div class="card-header" role="button">
          <p class="card-header-title">
            {{ category.description }}
          </p>
          <a class="card-header-icon">
            <b-icon :icon="props.open ? 'menu-down' : 'menu-up'"> </b-icon>
          </a>
        </div>
      </template>
      <div class="card-content">
        <div ref="content" class="content">
          <div v-for="item in categoryItems" :key="item.id" class="category-item">
            <b-icon icon="book-plus" size="is-small"> </b-icon>
            <a @click="selectedItem(item)" class="category-item-title">
              {{ item.description }}
            </a>
          </div>
          <b-loading :is-full-page="false" v-model="isLoading"></b-loading>
        </div>
      </div>
    </b-collapse>
  </section>

标签: node.jsvue.jsaxioslarge-data

解决方案


老实说,除了:

您应该对结果进行分页

什么是分页(假设您使用的是 REST API)

如果您真的想呈现所有这些结果,您仍然可以选择使用虚拟滚动条。虚拟滚动条允许您渲染数百万条记录,而无需在 DOM 中一次渲染所有记录。

如何使用虚拟滚动条超出了这个答案的范围。随意查看我发给你的链接


推荐阅读