search
HomeWeb Front-endJS TutorialBuild reusable pagination components with Vue

Build reusable pagination components with Vue

Mar 31, 2018 pm 05:38 PM
javascriptPaginationcomponents

Paging components are very common components in web projects. Let us use Vue to build reusable paging components. For the basic structure and related event monitoring, please refer to this article.

Resource paging in Web applications is not only Great for performance, but also very useful from a user experience perspective. In this article, learn how to create a dynamic and usable pagination component using Vue.

Basic Structure

The pagination component should allow the user to access the first and last pages, move forward and backward, and switch directly to the close page.

Most applications make an API request every time the user changes a page. We need to make sure that the component allows this, but we don't want to make such a request within the component. This way, we will ensure that components are reusable throughout the application and requests are made in the operation or service layer. We can do this by triggering an event using the number of the page the user clicked on.

There are several possible ways to implement pagination on API endpoints. For this example, we assume that the API tells us the number of results for each page, the total number of pages, and the current page. These will be our dynamic props.

In contrast, if the API only tells the total number of records, then we can calculate the number of pages by dividing the number of results by the number of results per page: totalResults / resultsPerPage .

We want to render a button to the first page, previous page, page number range, next page and last page:

[first] [next] [1] [2 ] [3] [previous] [last]

For example, an effect like the picture below:

Although we hope to render a series of pages, but does not want to render all available pages. Let's allow setting a prop for the most visible buttons in our component.

Now that we know what we want the component to do and what data it requires, we can set up the HTML structure and required props.


<template id="pagination">
  <ul class="pagination">
    <li>
      <button type="button">« First</button>
    </li>
    <li>
      <button type="button">«</button>
    </li>
    <!-- 页数的范围 -->
    <li>
      <button type="button">Next »</button>
    </li>
    <li>
      <button type="button">»</button>
    </li>
  </ul>
</template>
Vue.component(&#39;pagination&#39;, {
  template: &#39;#pagination&#39;,
  props: {
    maxVisibleButtons: {
      type: Number,
      required: false,
      default: 3
    },
    totalPages: {
      type: Number,
      required: true
    },
    total: {
      type: Number,
      required: true
    },
    currentPage: {
      type: Number,
      required: true
    }
  }
})


The above code registers a pagination component. If you call this component:


<p id="app">
  <pagination></pagination>
</p>


The effect you see at this time is as follows:


Note, in order to make the component look better , adds a little style to the component.

Event Listening

Now we need to notify the parent component which button the user clicked when the user clicks the button.

We need to add an event listener for each button. The v-on directive allows listening for DOM events. In this example, I'll use the v-on shortcut to listen for click events.

In order to notify the parent node, we will use the $emit method to emit an event with a page click.

We also need to ensure that the paging button only has a current state when the page is available. In order to do this, v-bind will be used to bind the value of the disabled attribute to the current page. We still use the :v-bind shortcut key: .

To keep our template clean, we will use the computed attribute to check if the button is disabled. Using computed is also cached, which means that as long as currentPage does not change, several accesses to the same computed property will return the previously computed result without having to run the function again.


<template id="pagination">
  <ul class="pagination">
    <li>
      <button type="button" @click="onClickFirstPage" :disabled="isInFirstPage">« First</button>
    </li>
    <li>
      <button type="button" @click="onClickPreviousPage" :disabled="isInFirstPage">«</button>
    </li>
    <li v-for="page in pages">
      <button type="button" @click="onClickPage(page.name)" :disabled="page.isDisabled"> {{ page.name }}</button>
    </li>
    <li>
      <button type="button" @click="onClickNextPage" :disabled="isInLastPage">Next »</button>
    </li>
    <li>
      <button type="button" @click="onClickLastPage" :disabled="isInLastPage">»</button>
    </li>
  </ul>
</template>

Vue.component(&#39;pagination&#39;, {
  template: &#39;#pagination&#39;,
  props: {
    maxVisibleButtons: {
      type: Number,
      required: false,
      default: 3
    },
    totalPages: {
      type: Number,
      required: true
    },
    total: {
      type: Number,
      required: true
    },
    currentPage: {
      type: Number,
      required: true
    }
  },
  computed: {
    isInFirstPage: function () {
      return this.currentPage === 1
    },
    isInLastPage: function () {
      return this.currentPage === this.totalPages
    }
  },
  methods: {
    onClickFirstPage: function () {
      this.$emit(&#39;pagechanged&#39;, 1)
    },
    onClickPreviousPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.currentPage - 1)
    },
    onClickPage: function (page) {
      this.$emit(&#39;pagechanged&#39;, page)
    },
    onClickNextPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.currentPage + 1)
    },
    onClickLastPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.totalPages)
    }
  }
})


When calling the pagination component, pass totalPages and total and currentPage to the component:


<p id="app">
  <pagination :total-pages="11" :total="120" :current-page="currentPage"></pagination>
</p>

let app = new Vue({
  el: &#39;#app&#39;,
  data () {
    return {
      currentPage: 2
    }
  }
})


When you run the above code, an error will be reported:


It is not difficult to find that in pagination Among the components, we are also missing pages. From what was introduced earlier, we can easily find that we need to calculate the value of pages.


Vue.component(&#39;pagination&#39;, {
  template: &#39;#pagination&#39;,
  props: {
    maxVisibleButtons: {
      type: Number,
      required: false,
      default: 3
    },
    totalPages: {
      type: Number,
      required: true
    },
    total: {
      type: Number,
      required: true
    },
    currentPage: {
      type: Number,
      required: true
    }
  },
  computed: {
    isInFirstPage: function () {
      return this.currentPage === 1
    },
    isInLastPage: function () {
      return this.currentPage === this.totalPages
    },
    startPage: function () {
      if (this.currentPage === 1) {
        return 1
      }
      if (this.currentPage === this.totalPages) {
        return this.totalPages - this.maxVisibleButtons + 1
      }
      return this.currentPage - 1
    },
    endPage: function () {
      return Math.min(this.startPage + this.maxVisibleButtons - 1, this.totalPages)
    },
    pages: function () {
      const range = []
      for (let i = this.startPage; i <= this.endPage; i+=1) {
        range.push({
          name: i,
          isDisabled: i === this.currentPage
        })
      }
      return range
    }
  },
  methods: {
    onClickFirstPage: function () {
      this.$emit(&#39;pagechanged&#39;, 1)
    },
    onClickPreviousPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.currentPage - 1)
    },
    onClickPage: function (page) {
      this.$emit(&#39;pagechanged&#39;, page)
    },
    onClickNextPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.currentPage + 1)
    },
    onClickLastPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.totalPages)
    }
  }
})


The result obtained at this time will no longer report an error. You will see the following effect in the browser:


Add styles

Now our component implements all the functionality we originally wanted, and Added some styling to make it look more like a pagination component rather than just a list.

We also want users to be able to clearly identify the page they are on. Let's change the color of the button representing the current page.

To do this, we can use object syntax to bind the HTML class to the current page button. When binding a class name using object syntax, Vue will automatically switch classes when the value changes.

虽然 v-for 中的每个块都可以访问父作用域范围,但是我们将使用 method 来检查页面是否处于 active 状态,以便保持我们的 templage 干净。


Vue.component(&#39;pagination&#39;, {
  template: &#39;#pagination&#39;,
  props: {
    maxVisibleButtons: {
      type: Number,
      required: false,
      default: 3
    },
    totalPages: {
      type: Number,
      required: true
    },
    total: {
      type: Number,
      required: true
    },
    currentPage: {
      type: Number,
      required: true
    }
  },
  computed: {
    isInFirstPage: function () {
      return this.currentPage === 1
    },
    isInLastPage: function () {
      return this.currentPage === this.totalPages
    },
    startPage: function () {
      if (this.currentPage === 1) {
        return 1
      }
      if (this.currentPage === this.totalPages) {
        return this.totalPages - this.maxVisibleButtons + 1
      }
      return this.currentPage - 1
    },
    endPage: function () {
      return Math.min(this.startPage + this.maxVisibleButtons - 1, this.totalPages)
    },
    pages: function () {
      const range = []
      for (let i = this.startPage; i <= this.endPage; i+=1) {
        range.push({
          name: i,
          isDisabled: i === this.currentPage
        })
      }
      return range
    }
  },
  methods: {
    onClickFirstPage: function () {
      this.$emit(&#39;pagechanged&#39;, 1)
    },
    onClickPreviousPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.currentPage - 1)
    },
    onClickPage: function (page) {
      this.$emit(&#39;pagechanged&#39;, page)
    },
    onClickNextPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.currentPage + 1)
    },
    onClickLastPage: function () {
      this.$emit(&#39;pagechanged&#39;, this.totalPages)
    },
    isPageActive: function (page) {
      return this.currentPage === page;
    }
  }
})


接下来,在 pages 中添加当前状态:


<li v-for="page in pages">
  <button type="button" @click="onClickPage(page.name)" :disabled="page.isDisabled" :class="{active: isPageActive(page.name)}"> {{ page.name }}</button>
</li>


这个时候你看到效果如下:

 

但依然还存在一点点小问题,当你在点击别的按钮时, active 状态并不会随着切换:

 

继续添加代码改变其中的效果:


let app = new Vue({
  el: &#39;#app&#39;,
  data () {
    return {
      currentPage: 2
    }
  },
  methods: {
    onPageChange: function (page) {
      console.log(page)
      this.currentPage = page;
    }
  }
})


在调用组件时:


<p id="app">
  <pagination :total-pages="11" :total="120" :current-page="currentPage" @pagechanged="onPageChange"></pagination>
</p>


这个时候的效果如下了:

 

到这里,基本上实现了咱想要的分页组件效果。

无障碍化处理

熟悉Bootstrap的同学都应该知道,Bootstrap中的组件都做了无障碍化的处理,就是在组件中添加了WAI-ARIA相关的设计。比如在分页按钮上添加 aria-label 相关属性:

 

在我们这个组件中,也相应的添加有关于WAI-ARIA相关的处理:


<template id="pagination">
  <ul class="pagination" aria-label="Page navigation">
    <li>
      <button type="button" @click="onClickFirstPage" :disabled="isInFirstPage" aria-label="Go to the first page">« First</button>
    </li>
    <li>
      <button type="button" @click="onClickPreviousPage" :disabled="isInFirstPage" aria-label="Previous">«</button>
    </li>
    <li v-for="page in pages">
      <button type="button" @click="onClickPage(page.name)" :disabled="page.isDisabled" :aria-label="`Go to page number ${page.name}`"> {{ page.name }}</button>
    </li>
    <li>
      <button type="button" @click="onClickNextPage" :disabled="isInLastPage" aria-label="Next">Next »</button>
    </li>
    <li>
      <button type="button" @click="onClickLastPage" :disabled="isInLastPage" aria-label="Go to the last page">»</button>
    </li>
  </ul>
</template>


这样有关于 aria 相关的属性就加上了:

 

最终的效果如下,可以点击下面的连接访问:


https://codepen.io/airen/pen/mxMLrG

相关推荐:

vue构建一个自动建站项目

vue构建多页面应用实例代码分享


The above is the detailed content of Build reusable pagination components with Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.