【问题标题】:Pagination Logic - Vue分页逻辑 - Vue
【发布时间】:2021-05-21 05:30:26
【问题描述】:

嘿,希望有人能帮助我,我开始了一份新工作,我的大脑已经完全变成废话,看似简单的任务现在给我带来了问题,就像我在上一份工作中离开了我的大脑?无论如何,我有一些分页,我正在尝试为其构建逻辑。

我有一个 v-for 循环遍历数据以使用索引号作为页码来构建分页。我也知道活跃的页码和总页数。我使用 v-if 来显示或隐藏分页项。我想在任何时候显示 8 个项目并隐藏其余项目,因此如果第 2 页处于活动状态,则会显示项目 2-9 并隐藏其余项目,该部分工作正常。我想要做的是当我接近列表末尾时,我仍然想在屏幕上保留 8 个项目并且活动项目只是前进,即总共 9 个项目,项目 2 设置为活动并且在屏幕上我可以看到项目2-9,当我单击下一步时,我仍然希望屏幕上有 8 个项目(2-9),但现在活动项目是项目 3,依此类推。这可以使用 v-if 来完成,还是我失去了情节并试图实现不可能?

<div v-for="index in totalPages" :key="index">
              <div
                v-if="
                  index >= activeItem &&
                  index < activeItem + onScreenTotal
                "
                :class="index === activeItem ? 'active' : null"
              >
                {{ index }}
              </div>
            </div>
  • totalPages = 分页项的总数
  • activeItem = 活动页面项
  • onScreenTotal = 我想在任何时候在屏幕上显示多少项目

【问题讨论】:

    标签: javascript vue.js pagination logic


    【解决方案1】:

    您可以使用一些Math.min(..)Math.max(..) 调用,但您的模板会变得非常混乱。我建议将逻辑移至计算属性。您可以从当前页面开始,也可以从结束前的this.onScreenTotal 页开始,如果您的页面少于this.onScreenTotal,您希望从第 1 页开始,而不是从 0 或某个负数开始。你可以用同样的方法计算结尾,只是我们永远不会超过我们拥有的页数。

    <template v-for="index in visiblePages">
      <div :key="index" :class="{ active: index === activeItem }">
        {{ index }}
      </div>
    </template>
    
    // And in your javascript
    computed: {
      visiblePages() {
        const pages = [];
        const start = Math.max(1, Math.min(this.activeItem, this.totalPages - this.onScreenTotal));
        const end = Math.min(start + this.onScreenTotal, this.onScreenTotal);
    
        for (const i = start; i <= end; i++) {
          pages.push(i);
        }
    
        return pages;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2014-03-15
      • 2016-03-22
      相关资源
      最近更新 更多