当前位置:首页 > 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分页的几种方法 使用Element UI的分页组件 安装Element UI库后,可以直接使用其分页组件。以下是一个基本示例: <template> <div>…

vue实现下拉框组件

vue实现下拉框组件

Vue 下拉框组件实现 基础实现 创建基础下拉框组件,使用v-model实现双向数据绑定: <template> <div class="dropdown"> &…

uniapp如何将底部导航组件化

uniapp如何将底部导航组件化

在 uniapp 中将底部导航组件化 将底部导航组件化可以提高代码复用性和维护性。以下是具体实现方法: 创建自定义底部导航组件 新建一个组件文件,例如 tab-bar.vue,放置在 compon…

vue VUE实现日历组件功能

vue VUE实现日历组件功能

Vue 日历组件实现方法 基础日历结构 使用Vue的模板语法构建日历的HTML结构,通常包含头部(年月显示、切换按钮)和日历表格(星期标题和日期格子)。 <template> <…

vue动态组件实现

vue动态组件实现

动态组件的基本用法 在Vue中,动态组件通过<component>标签和is属性实现。is属性可以绑定组件名称或组件选项对象,实现动态切换。 <template> <…

vue实现tooltips组件

vue实现tooltips组件

实现基础 Tooltip 组件 创建一个名为 Tooltip.vue 的单文件组件,包含模板、样式和逻辑: <template> <div class="tooltip-con…