vue组件传值实现分页
Vue组件传值实现分页的方法
父子组件传值(Props + $emit)
父组件通过props向子组件传递分页数据(如当前页码、每页条数),子组件通过$emit触发父组件的方法更新数据。
父组件代码示例:
<template>
<child-component
:current-page="currentPage"
:page-size="pageSize"
@page-change="handlePageChange"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10
}
},
methods: {
handlePageChange(newPage) {
this.currentPage = newPage;
this.fetchData();
}
}
}
</script>
子组件代码示例:
<template>
<button @click="$emit('page-change', currentPage + 1)">下一页</button>
</template>
<script>
export default {
props: ['currentPage', 'pageSize']
}
</script>
使用Vuex状态管理
适用于跨层级组件或复杂分页逻辑,将分页数据存储在Vuex中,通过mapState和mapMutations访问或修改。
Vuex store示例:
const store = new Vuex.Store({
state: {
pagination: {
currentPage: 1,
pageSize: 10
}
},
mutations: {
SET_PAGE(state, page) {
state.pagination.currentPage = page;
}
}
});
组件调用示例:
<template>
<button @click="setPage(currentPage + 1)">下一页</button>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['pagination']),
currentPage() {
return this.pagination.currentPage;
}
},
methods: {
...mapMutations(['SET_PAGE']),
setPage(page) {
this.SET_PAGE(page);
}
}
}
</script>
事件总线(Event Bus)
适用于非父子关系的组件通信,通过全局事件总线传递分页事件。
创建事件总线:
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
发送事件组件:
EventBus.$emit('page-changed', 2);
接收事件组件:
EventBus.$on('page-changed', (page) => {
this.currentPage = page;
});
使用provide/inject
适用于深层嵌套组件,祖先组件通过provide提供分页数据,后代组件通过inject获取。
祖先组件:
export default {
provide() {
return {
pagination: {
currentPage: this.currentPage,
setPage: this.setPage
}
}
}
}
后代组件:
export default {
inject: ['pagination'],
methods: {
nextPage() {
this.pagination.setPage(this.pagination.currentPage + 1);
}
}
}
路由参数分页
通过URL路由参数管理分页状态,适合需要分享或书签的场景。
路由配置:
{
path: '/list/:page',
component: List
}
组件内获取页码:
this.$route.params.page
切换页码:

this.$router.push(`/list/${newPage}`)






