当前位置:首页 > VUE

vue router实现分页

2026-03-28 04:49:08VUE

使用 Vue Router 实现分页功能

在 Vue.js 项目中,可以通过 Vue Router 结合动态路由和查询参数来实现分页功能。以下是具体实现方法:

配置动态路由

router/index.js 中配置动态路由参数 page,用于捕获当前页码:

const routes = [
  {
    path: '/list/:page?',
    name: 'List',
    component: () => import('../views/List.vue'),
    props: true
  }
]

组件内处理分页逻辑

在列表组件中,通过 watch 监听路由参数变化,并加载对应页码的数据:

export default {
  props: ['page'],
  data() {
    return {
      currentPage: 1,
      items: [],
      totalPages: 0
    }
  },
  watch: {
    page: {
      immediate: true,
      handler(newPage) {
        this.currentPage = newPage ? parseInt(newPage) : 1
        this.fetchData()
      }
    }
  },
  methods: {
    fetchData() {
      // 模拟API请求
      const mockData = {
        data: [...], // 当前页数据
        total: 100   // 总数据量
      }

      this.items = mockData.data
      this.totalPages = Math.ceil(mockData.total / 10)
    },
    changePage(newPage) {
      if (newPage > 0 && newPage <= this.totalPages) {
        this.$router.push(`/list/${newPage}`)
      }
    }
  }
}

模板中的分页控件

在模板中添加分页导航,使用 router-link 或编程式导航:

<template>
  <div>
    <!-- 列表内容 -->
    <div v-for="item in items" :key="item.id">
      {{ item.name }}
    </div>

    <!-- 分页控件 -->
    <div class="pagination">
      <button 
        @click="changePage(currentPage - 1)"
        :disabled="currentPage === 1"
      >
        上一页
      </button>

      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>

      <button 
        @click="changePage(currentPage + 1)"
        :disabled="currentPage === totalPages"
      >
        下一页
      </button>
    </div>
  </div>
</template>

使用查询参数替代动态路由

如果需要更灵活的分页方案,可以使用查询参数:

// 路由配置
{
  path: '/list',
  name: 'List',
  component: () => import('../views/List.vue')
}

// 组件内导航方法
changePage(newPage) {
  this.$router.push({
    path: '/list',
    query: { page: newPage }
  })
}

// 获取当前页
this.currentPage = parseInt(this.$route.query.page) || 1

处理初始页面加载

created 生命周期中处理初始页面加载:

vue router实现分页

created() {
  if (!this.page && this.$route.params.page) {
    this.currentPage = parseInt(this.$route.params.page)
  }
  this.fetchData()
}

这种方法实现了基于 Vue Router 的分页功能,保持了 URL 与页面状态的同步,支持浏览器前进/后退导航,并可以通过直接输入URL访问特定页码。

标签: 分页vue
分享给朋友:

相关文章

实现vue模版

实现vue模版

Vue 模板的基本结构 Vue 模板基于 HTML 语法,通过 Vue 的指令和插值实现动态渲染。以下是一个基础模板示例: <template> <div id="…

vue实现前端

vue实现前端

Vue 实现前端的核心方法与步骤 安装 Vue 项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 是传统构建工具,Vite 是新一代轻量级工具。 npm init vue@la…

vue实现radio

vue实现radio

Vue 实现 Radio 按钮 在 Vue 中实现 Radio 按钮可以通过 v-model 进行数据绑定,结合 input 元素的 type="radio" 属性。以下是一个基本示例: <t…

vue实现表单

vue实现表单

Vue 表单实现方法 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定。适用于 input、textarea、select 等元素。 <template> <…

vue 实现 confirm

vue 实现 confirm

实现确认对话框的方法 在Vue中实现确认对话框可以通过多种方式完成,包括使用内置组件、第三方库或自定义组件。 使用浏览器原生confirm 最简单的实现方式是直接调用浏览器原生的confirm方法。…

vue实现列表

vue实现列表

Vue 实现列表的方法 在 Vue 中实现列表渲染通常使用 v-for 指令,可以动态生成多个元素。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 遍历数组,生成列表项。v-for 需要…