【问题标题】:Slow performance when fetching and rendering large dataset in vue/nuxt在 vue/nuxt 中获取和渲染大型数据集时性能下降
【发布时间】:2021-12-03 05:06:20
【问题描述】:

好的,我的情况如下...我必须根据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>

【问题讨论】:

  • 您确定要一次提取这么多数据吗?任何一次用这么多新数据渲染到 DOM 的库都会很慢。您可以尝试分页或轮询数据以提高性能

标签: node.js vue.js axios large-data


【解决方案1】:

老实说,除了:

你应该对结果进行分页

What is pagination(假设您使用的是 REST API)

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

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

【讨论】:

  • 分页就像一个魅力!我不得不改变我显示数据的方式,但现在它看起来不错并且运行顺利!谢谢,伙计
猜你喜欢
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多