当前位置:首页 > 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实现组件跟随

实现组件跟随的常见方法 使用CSS定位 通过CSS的position: fixed或position: absolute属性实现组件跟随。需要结合JavaScript计算目标元素的位置。 &…

uniapp组件写法

uniapp组件写法

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

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

vue实现折叠组件

vue实现折叠组件

实现折叠组件的基本思路 在Vue中实现折叠组件通常需要利用动态绑定和条件渲染。核心是通过控制一个布尔值状态来决定内容是否显示,并添加过渡动画提升用户体验。 基础实现方法 使用v-show或v-if控…

jquery 分页

jquery 分页

实现 jQuery 分页的方法 客户端分页实现 使用 jQuery 实现客户端分页的核心思路是通过 JavaScript 控制数据的显示与隐藏。假设有一个包含数据的 HTML 列表或表格: // 分…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现 Vue组件是Vue.js的核心概念之一,允许将UI拆分为独立可复用的代码片段。组件的实现方式有多种,以下是常见的几种方法。 单文件组件(SFC) 单文件组件以.vue为后缀,将…