vue组件传值实现分页
Vue组件传值实现分页的方法
在Vue中实现分页功能通常需要父子组件之间的数据传递,以下是几种常见的实现方式:
使用props和$emit
父组件通过props将分页数据传递给子组件,子组件通过$emit触发事件通知父组件页码变化。
父组件代码:
<template>
<div>
<child-component
:current-page="currentPage"
:total-items="totalItems"
@page-changed="handlePageChange"
/>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
totalItems: 100
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
// 这里可以添加获取新页数据的逻辑
}
}
}
</script>
子组件代码:
<template>
<div>
<button @click="prevPage">上一页</button>
<span>{{ currentPage }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
props: ['currentPage', 'totalItems'],
methods: {
prevPage() {
if (this.currentPage > 1) {
this.$emit('page-changed', this.currentPage - 1)
}
},
nextPage() {
if (this.currentPage < Math.ceil(this.totalItems / 10)) {
this.$emit('page-changed', this.currentPage + 1)
}
}
}
}
</script>
使用Vuex状态管理
对于复杂应用,可以使用Vuex集中管理分页状态。
store代码:

const store = new Vuex.Store({
state: {
currentPage: 1,
totalItems: 100
},
mutations: {
SET_CURRENT_PAGE(state, page) {
state.currentPage = page
}
}
})
组件代码:
<template>
<div>
<button @click="prevPage">上一页</button>
<span>{{ currentPage }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
computed: {
...mapState(['currentPage', 'totalItems'])
},
methods: {
...mapMutations(['SET_CURRENT_PAGE']),
prevPage() {
if (this.currentPage > 1) {
this.SET_CURRENT_PAGE(this.currentPage - 1)
}
},
nextPage() {
if (this.currentPage < Math.ceil(this.totalItems / 10)) {
this.SET_CURRENT_PAGE(this.currentPage + 1)
}
}
}
}
</script>
使用provide/inject
对于深层嵌套组件,可以使用provide/inject传递分页数据。
祖先组件:
export default {
provide() {
return {
pagination: {
currentPage: this.currentPage,
changePage: this.changePage
}
}
},
data() {
return {
currentPage: 1
}
},
methods: {
changePage(page) {
this.currentPage = page
}
}
}
后代组件:

export default {
inject: ['pagination'],
methods: {
handlePageChange(page) {
this.pagination.changePage(page)
}
}
}
使用事件总线
对于非父子关系的组件,可以使用事件总线实现通信。
创建事件总线:
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
发送事件组件:
EventBus.$emit('page-changed', newPage)
接收事件组件:
EventBus.$on('page-changed', (page) => {
// 处理页码变化
})
每种方法都有其适用场景,props/$emit适合简单父子组件通信,Vuex适合大型应用状态管理,provide/inject适合深层嵌套组件,事件总线适合非父子关系组件通信。






