vue组件传值实现分页
vue组件传值实现分页的方法
父组件向子组件传递分页数据
通过props将分页相关数据(如当前页码、每页条数)传递给子组件。父组件定义分页数据,子组件通过props接收并使用。
<!-- 父组件 -->
<template>
<child-component
:current-page="currentPage"
:page-size="pageSize"
:total="total"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
}
}
</script>
<!-- 子组件 -->
<script>
export default {
props: ['currentPage', 'pageSize', 'total']
}
</script>
子组件向父组件传递分页变更
子组件通过$emit触发事件,父组件监听事件并更新分页数据。通常用于页码切换或每页条数调整。

<!-- 子组件 -->
<template>
<button @click="$emit('page-change', 2)">跳转到第2页</button>
</template>
<!-- 父组件 -->
<template>
<child-component @page-change="handlePageChange" />
</template>
<script>
export default {
methods: {
handlePageChange(newPage) {
this.currentPage = newPage;
this.fetchData(); // 重新获取数据
}
}
}
</script>
使用Vuex管理分页状态
在大型项目中,可通过Vuex集中管理分页状态。组件通过mapState获取分页数据,通过commit或dispatch更新状态。

// store.js
export default new Vuex.Store({
state: {
pagination: {
currentPage: 1,
pageSize: 10
}
},
mutations: {
SET_PAGE(state, payload) {
state.pagination.currentPage = payload;
}
}
});
// 组件中使用
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['pagination'])
},
methods: {
...mapMutations(['SET_PAGE']),
changePage(page) {
this.SET_PAGE(page);
}
}
}
</script>
使用事件总线(Event Bus)
对于非父子关系的组件,可通过全局事件总线实现通信。创建一个Vue实例作为事件中心,组件通过$on和$emit交互。
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
// 组件A(发送事件)
EventBus.$emit('page-updated', { page: 2 });
// 组件B(接收事件)
EventBus.$on('page-updated', payload => {
console.log(payload.page);
});
使用provide/inject
祖先组件通过provide提供分页数据,后代组件通过inject注入使用。适用于深层嵌套的组件结构。
// 祖先组件
export default {
provide() {
return {
pagination: {
currentPage: this.currentPage,
setPage: this.setPage
}
};
}
}
// 后代组件
export default {
inject: ['pagination'],
methods: {
handleClick() {
this.pagination.setPage(3);
}
}
}
注意事项
- 单向数据流:props传递的数据应避免在子组件直接修改,需通过事件通知父组件变更。
- 性能优化:频繁的分页操作可结合防抖(debounce)减少请求次数。
- 组件解耦:若分页逻辑复杂,建议将分页控件封装为独立组件,通过插槽(slot)灵活布局。






