当前位置:首页 > VUE

vue组件传值实现分页

2026-03-27 03:41:21VUE

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中,通过mapStatemapMutations访问或修改。

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

切换页码:

vue组件传值实现分页

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

标签: 分页组件
分享给朋友:

相关文章

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

Vue 拖拽实现组件嵌套 使用 Vue 实现拖拽组件嵌套功能可以通过原生 HTML5 拖拽 API 或第三方库如 vuedraggable 实现。以下是两种方法的详细说明: 使用 HTML5 拖拽…

uniapp组件写法

uniapp组件写法

Uniapp 组件的基本写法 Uniapp 的组件写法与 Vue 类似,支持单文件组件(.vue 文件)。一个基本的组件通常包含三个部分:<template>、<script>…

vue实现组件

vue实现组件

Vue 实现组件的方法 Vue 中实现组件可以通过多种方式,包括全局注册、局部注册、单文件组件(SFC)等。以下是常见的实现方法。 全局注册组件 全局注册的组件可以在任何 Vue 实例或组件中使用。…

vue实现分页条数

vue实现分页条数

Vue 实现分页条数控制 在 Vue 中实现分页条数控制通常需要结合分页组件和后端 API 支持。以下是几种常见的实现方式: 使用 Element UI 的分页组件 Element UI 提供了强大…

vue轮播组件实现

vue轮播组件实现

vue轮播组件实现方法 使用第三方库(如Swiper) 安装Swiper库: npm install swiper 在Vue组件中引入: <template> <div cl…

vue实现页面分页

vue实现页面分页

Vue实现页面分页的方法 使用Element UI的分页组件 Element UI提供了现成的分页组件el-pagination,适合快速集成。以下是一个示例代码: <template>…