vue Bootstrap实现分页
Vue Bootstrap 分页实现方法
在 Vue 项目中结合 Bootstrap 实现分页功能,可以通过以下步骤完成。这里假设项目已经配置好 Vue 和 Bootstrap 环境。
安装依赖
确保项目中已安装 Bootstrap 和 Vue Bootstrap 相关依赖。如果没有安装,可以通过以下命令添加:
npm install bootstrap @popperjs/core
npm install bootstrap-vue@next
引入 Bootstrap 样式
在项目的入口文件(如 main.js 或 main.ts)中引入 Bootstrap 样式和 Vue Bootstrap 组件:
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import { BootstrapVue, BPagination } from 'bootstrap-vue'
Vue.use(BootstrapVue)
Vue.component('b-pagination', BPagination)
基本分页组件
在 Vue 组件中使用 b-pagination 实现基础分页功能:
<template>
<div>
<b-pagination
v-model="currentPage"
:total-rows="totalRows"
:per-page="perPage"
aria-controls="my-table"
></b-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
totalRows: 100,
perPage: 10
}
}
}
</script>
分页与表格数据绑定
将分页组件与表格数据绑定,实现分页显示数据:
<template>
<div>
<b-table
id="my-table"
:items="items"
:per-page="perPage"
:current-page="currentPage"
></b-table>
<b-pagination
v-model="currentPage"
:total-rows="totalRows"
:per-page="perPage"
aria-controls="my-table"
></b-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
perPage: 5,
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// 更多数据...
]
}
},
computed: {
totalRows() {
return this.items.length
}
}
}
</script>
自定义分页外观
可以通过 props 自定义分页组件的外观和行为:
<b-pagination
v-model="currentPage"
:total-rows="totalRows"
:per-page="perPage"
pills
size="sm"
align="center"
first-number
last-number
></b-pagination>
分页事件处理
监听分页变化事件,可以在数据变化时执行特定操作:
<b-pagination
v-model="currentPage"
:total-rows="totalRows"
:per-page="perPage"
@change="onPageChange"
></b-pagination>
methods: {
onPageChange(page) {
console.log('当前页码:', page)
// 可以在这里发起API请求获取新页数据
}
}
服务器端分页
对于大数据量场景,可以实现服务器端分页:

methods: {
fetchData(page) {
axios.get(`/api/items?page=${page}&per_page=${this.perPage}`)
.then(response => {
this.items = response.data.items
this.totalRows = response.data.total
})
},
onPageChange(page) {
this.fetchData(page)
}
},
created() {
this.fetchData(1)
}
以上方法提供了在 Vue 项目中使用 Bootstrap 实现分页功能的完整方案,从基础实现到高级定制都有涵盖。根据实际项目需求,可以选择适合的实现方式。






