vue加载实现分页
Vue 实现分页加载的方法
使用第三方库(如 Element UI)
Element UI 提供了现成的分页组件 el-pagination,可以快速实现分页功能。安装 Element UI 后,在组件中引入并使用分页组件。
<template>
<div>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 根据 currentPage 和 pageSize 请求数据
}
}
}
</script>
手动实现分页逻辑

如果不使用第三方库,可以手动实现分页逻辑。通过计算属性或方法对数据进行分页处理。
<template>
<div>
<div v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</div>
<button @click="prevPage">上一页</button>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
data: [],
currentPage: 1,
pageSize: 10
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.data.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < Math.ceil(this.data.length / this.pageSize)) {
this.currentPage++
}
}
}
}
</script>
结合后端 API 实现分页

通常分页数据由后端提供,前端只需传递当前页码和每页大小。后端返回对应的数据及总条数。
<template>
<div>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
data: []
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.data = res.data.list
this.total = res.data.total
}
},
created() {
this.fetchData()
}
}
</script>
无限滚动分页
对于移动端或需要流畅体验的场景,可以使用无限滚动分页。监听滚动事件,滚动到底部时加载更多数据。
<template>
<div ref="scrollContainer" @scroll="handleScroll">
<div v-for="item in data" :key="item.id">
{{ item.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
data: [],
currentPage: 1,
pageSize: 10,
isLoading: false,
hasMore: true
}
},
methods: {
handleScroll() {
const container = this.$refs.scrollContainer
if (container.scrollTop + container.clientHeight >= container.scrollHeight - 100 && !this.isLoading && this.hasMore) {
this.loadMore()
}
},
async loadMore() {
this.isLoading = true
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.data = [...this.data, ...res.data.list]
this.currentPage++
this.hasMore = res.data.list.length === this.pageSize
this.isLoading = false
}
},
created() {
this.loadMore()
}
}
</script>






