Detailed explanation of steps to build paging component in Vue
This time I will bring you a detailed explanation of the steps to build a paging component in Vue. What are the precautions for building a paging component in Vue? Here are practical cases, let’s take a look.
Paging resources in web applications is not only helpful 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 one below:
Although we want to render a series of pages, It is not expected 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> <ul> <li> <button>« First</button> </li> <li> <button>«</button> </li> <!-- 页数的范围 --> <li> <button>Next »</button> </li> <li> <button>»</button> </li> </ul> </template> Vue.component('pagination', { template: '#pagination', 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> <pagination></pagination> </p>
The effect you see at this time is as follows:
Note that in order to make the component look better, a little style is added 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> <ul> <li> <button>« First</button> </li> <li> <button>«</button> </li> <li> <button> {{ page.name }}</button> </li> <li> <button>Next »</button> </li> <li> <button>»</button> </li> </ul> </template> Vue.component('pagination', { template: '#pagination', 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('pagechanged', 1) }, onClickPreviousPage: function () { this.$emit('pagechanged', this.currentPage - 1) }, onClickPage: function (page) { this.$emit('pagechanged', page) }, onClickNextPage: function () { this.$emit('pagechanged', this.currentPage + 1) }, onClickLastPage: function () { this.$emit('pagechanged', this.totalPages) } } })
When calling the pagination component, pass totalPages, total and currentPage to the component:
<p> <pagination></pagination> </p> let app = new Vue({ el: '#app', data () { return { currentPage: 2 } } })
When you run the above code, an error will be reported:
It is not difficult to find that in the pagination component, we are missing pages. From what was introduced earlier, we can easily find that we need to calculate the value of pages.
Vue.component('pagination', { template: '#pagination', 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 <p style="text-align: left;">The result obtained at this time will no longer report an error. You will see the following effect in the browser: </p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/42ed7f3b40c11537a15fd174041da49c-3.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""> </p><p style="max-width:90%"><span style="color: #ff0000"><strong>Add style</strong></span></p><p style="text-align: left;">现在我们的组件实现了最初想要的所有功能,而且添加了一些样式,让它看起来更像一个分页组件,而不仅像是一个列表。</p><p style="text-align: left;">我们还希望用户能够清楚地识别他们所在的页面。让我们改变表示当前页面的按钮的颜色。</p><p style="text-align: left;">为此,我们可以使用对象语法将HTML类绑定到当前页面按钮上。当使用对象语法绑定类名时,Vue将在值发生变化时自动切换类。</p><p style="text-align: left;">虽然 v-for 中的每个块都可以访问父作用域范围,但是我们将使用 method 来检查页面是否处于 active 状态,以便保持我们的 templage 干净。</p><pre class="brush:php;toolbar:false">Vue.component('pagination', { template: '#pagination', 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 <p style="text-align: left;">接下来,在 pages 中添加当前状态:</p><pre class="brush:php;toolbar:false">
这个时候你看到效果如下:
但依然还存在一点点小问题,当你在点击别的按钮时, active 状态并不会随着切换:
继续添加代码改变其中的效果:
let app = new Vue({ el: '#app', data () { return { currentPage: 2 } }, methods: { onPageChange: function (page) { console.log(page) this.currentPage = page; } } })
在调用组件时:
<p> <pagination></pagination> </p>
这个时候的效果如下了:
到这里,基本上实现了咱想要的分页组件效果。
无障碍化处理
熟悉Bootstrap的同学都应该知道,Bootstrap中的组件都做了无障碍化的处理,就是在组件中添加了WAI-ARIA相关的设计。比如在分页按钮上添加 aria-label 相关属性:
在我们这个组件中,也相应的添加有关于WAI-ARIA相关的处理:
<template> <ul> <li> <button>« First</button> </li> <li> <button>«</button> </li> <li> <button> {{ page.name }}</button> </li> <li> <button>Next »</button> </li> <li> <button>»</button> </li> </ul> </template>
这样有关于 aria 相关的属性就加上了:
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of steps to build paging component in Vue. For more information, please follow other related articles on the PHP Chinese website!

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.

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 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 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 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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool