vue实现翻页
Vue实现翻页功能
使用v-for和计算属性
在Vue中实现翻页功能可以通过计算属性来分割数据,结合v-for指令渲染当前页的数据。
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// 更多数据...
],
currentPage: 1,
itemsPerPage: 5
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
使用第三方库
对于更复杂的分页需求,可以使用专门的分页组件库,如vuejs-paginate。

安装库:

npm install vuejs-paginate
使用示例:
<template>
<div>
<paginate
v-model="currentPage"
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'<'"
:next-text="'>'"
/>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
import Paginate from 'vuejs-paginate'
export default {
components: {
Paginate
},
data() {
return {
items: [], // 数据数组
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
changePage(pageNum) {
this.currentPage = pageNum
}
}
}
</script>
服务器端分页
对于大数据量,建议使用服务器端分页,通过API请求获取当前页数据。
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="fetchData(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="fetchData(currentPage + 1)" :disabled="isLastPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
currentPage: 1,
isLastPage: false
}
},
methods: {
async fetchData(page) {
try {
const response = await axios.get(`/api/items?page=${page}`)
this.items = response.data.items
this.currentPage = page
this.isLastPage = response.data.isLastPage
} catch (error) {
console.error(error)
}
}
},
created() {
this.fetchData(1)
}
}
</script>
以上方法可以根据实际需求选择适合的方案实现Vue翻页功能。






