如何限制Vue中的分页按钮?

Bob*_*aru 3 javascript pagination vue.js vue-component vuejs2

我有一个分页组件,它接收totalPagescurrentPage支持,然后渲染更改currentPage. 问题是,现在如果我有很多产品,我会渲染太多按钮,并且我想将按钮数量限制为 5 个 - 前两页、当前页面和后两页。

因此,如果我的当前页面是4,我会看到页面按钮2, 3, 4, 5, 6,并且当前页面始终是中间按钮(除非这是不可能的)。我不太确定如何处理这个问题,特别是当是currentPage第一个/第二个或倒数第二个/最后一个时的极端情况。

<template lang="html">
    <div class="pagination">
        <div v-for="page in totalPages">
            <div class="page" :class="{ active: page == currentPage}"  @click="setCurrentPage(page)">{{ page }}</div>
        </div>
    </div>
</template>

<script>
export default {
    props: ["totalPages", "currentPage"],
    methods: {
        setCurrentPage(page){
            this.$emit("setCurrentPage", page);
        }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 7

对于在极端情况下也显示完整集的分页,请使用以下算法。这个想法是计算正确的起始索引,然后根据它生成一个数组:

computed: {
  pages() {
    let numShown = 5;   // This sets the number of page tabs
    numShown = Math.min(numShown, this.totalPages);
    let first = this.currentPage - Math.floor(numShown / 2);
    first = Math.max(first, 1);
    first = Math.min(first, this.totalPages - numShown + 1);
    return [...Array(numShown)].map((k,i) => i + first);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示(我更改了一些变量名称):

Vue.component('child', {
  props: ["total", "current"],
  template: `
  <div class="pagination">
    <template v-for="page in pages">
      <div
        :class="{ active: page == current }" class="page no-select"
        @click="setCurrent(page)"
      >
        {{ page }}
      </div>
    </template>
  </div>
  `,
  data: () => ({
    numShown: 5
  }),
  computed: {
    pages() {
      const numShown = Math.min(this.numShown, this.total);
      let first = this.current - Math.floor(numShown / 2);
      first = Math.max(first, 1);
      first = Math.min(first, this.total - numShown + 1);
      return [...Array(numShown)].map((k,i) => i + first);
    }
  },
  methods: {
    setCurrent(page){
      this.$emit("set", page);
    }
  }
})

new Vue({
  el: "#app",
  data: () => ({
    total: 8,
    current: 1
  })
});
Run Code Online (Sandbox Code Playgroud)
.page {
  display: inline-block;
  background: #dddddd;
  padding: 6px 16px;
  cursor: pointer;
  font-family: 'Helvetica';
  font-size: 13pt;
}
.active {
  background: #ddeeff;
  font-weight: bold;
}
.no-select {
  user-select: none;
  -o-user-select:none;
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
}
Run Code Online (Sandbox Code Playgroud)
<div id="app">
  <child :total="total" :current="current" @set="current = $event"></child>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢分享这个算法。它最近在我正在编写的一个需要分页的应用程序中为我提供了帮助。 (2认同)