vue如何实现分业
Vue 实现分页的方法
在 Vue 中实现分页功能通常需要结合后端 API 或前端数据处理。以下是几种常见的实现方式:
使用第三方库
Vue 生态中有许多成熟的分页组件库,例如 vue-paginate 或 element-ui 的分页组件。以 element-ui 为例:

<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 调用 API 获取数据
}
}
}
</script>
自定义分页组件
如果需要完全自定义分页逻辑,可以手动实现:

<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: {
type: Number,
default: 10
}
},
data() {
return {
currentPage: 1
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.$emit('page-changed', this.currentPage)
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.$emit('page-changed', this.currentPage)
}
}
}
}
</script>
前端数据分页
如果数据量不大,可以在前端进行分页处理:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage">上一页</button>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 5,
allData: [] // 所有数据
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
},
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
}
</script>
与后端 API 配合
实际项目中,分页通常需要与后端 API 配合:
methods: {
async fetchData(page = 1) {
const response = await axios.get('/api/items', {
params: {
page,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
}
}
以上方法可以根据项目需求选择使用,第三方组件库适合快速开发,自定义组件提供更大灵活性,前端分页适合小数据集,后端分页适合大数据量场景。





