Vue.js中如何为bootstrap-vue分页组件各页码绑定事件触发接口请求
实现方案
你可以通过两种方式监听页码切换,执行自定义逻辑:
- 方案1:使用
<b-pagination>组件自带的切换事件<b-pagination>组件在页码变更时会触发change事件,回调参数为切换后的目标页码,你可以直接绑定该事件实现需求。
修改后的代码示例:
<template> <div class="overflow-auto"> <b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" @change="handlePageChange" ></b-pagination> <p class="mt-3">Current Page: {{ currentPage }}</p> <b-table :items="items" :per-page="perPage" :current-page="currentPage" ></b-table> </div> </template>
<script> export default { data() { return { perPage: 3, currentPage: 1, items: [ { id: 1, first_name: 'Fred', last_name: 'Flintstone' }, { id: 2, first_name: 'Wilma', last_name: 'Flintstone' }, { id: 3, first_name: 'Barney', last_name: 'Rubble' }, { id: 4, first_name: 'Betty', last_name: 'Rubble' }, { id: 5, first_name: 'Pebbles', last_name: 'Flintstone' }, { id: 6, first_name: 'Bamm Bamm', last_name: 'Rubble' }, { id: 7, first_name: 'The Great', last_name: 'Gazzoo' }, { id: 8, first_name: 'Rockhead', last_name: 'Slate' }, { id: 9, first_name: 'Pearl', last_name: 'Slaghoople' } ] } }, computed: { rows() { return this.items.length } }, methods: { handlePageChange(newPage) { // 此处写入自定义逻辑,例如发起API请求获取对应页数据 console.log('切换到页码:', newPage) // 接口请求参考逻辑: // axios.get('/api/list', { params: { page: newPage, pageSize: this.perPage } }).then(res => { // this.items = res.data.list // this.rows = res.data.total // }) } } } </script>
- 方案2:监听
currentPage变量的变化
因为你已经用v-model把分页组件和currentPage变量双向绑定了,页码切换时currentPage的值会自动更新,你也可以通过watch监听该变量的变化触发逻辑:
// 在组件配置中添加watch项 watch: { currentPage(newVal, oldVal) { // 此处执行自定义逻辑 console.log('页码从', oldVal, '切换为', newVal) } }
如果是服务端分页场景,直接在上述事件/监听回调中发起接口请求,将接口返回的列表数据赋值给items、总条数赋值给rows即可完成分页渲染。
内容的提问来源于stack exchange,提问作者T dhanunjay
相关产品推荐
相关产品推荐

