Springboot整合vue实现分页
SpringBoot 整合 Vue 实现分页
后端实现 (SpringBoot)
-
创建分页查询接口 在 Controller 中定义一个接口,接收页码和每页大小参数,返回分页数据。
@GetMapping("/api/users") public Page<User> getUsers( @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size) { Pageable pageable = PageRequest.of(page - 1, size); return userRepository.findAll(pageable); } -
添加分页依赖 确保项目中包含 Spring Data JPA 依赖,用于支持分页功能。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> -
配置跨域支持 由于前端和后端可能运行在不同端口,需要配置跨域支持。
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/") .allowedOrigins("*") .allowedMethods("*"); } }
前端实现 (Vue)
-
安装 axios 使用 axios 进行 HTTP 请求。
npm install axios -
创建分页组件 在 Vue 组件中实现分页逻辑和数据获取。
<template> <div> <table> <tr v-for="user in users" :key="user.id"> <td>{{ user.name }}</td> </tr> </table> <div> <button @click="prevPage" :disabled="currentPage === 1">上一页</button> <span>第 {{ currentPage }} 页</span> <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { users: [], currentPage: 1, totalPages: 0, pageSize: 10 }; }, methods: { fetchUsers() { axios.get(`/api/users?page=${this.currentPage}&size=${this.pageSize}`) .then(response => { this.users = response.data.content; this.totalPages = response.data.totalPages; }); }, prevPage() { if (this.currentPage > 1) { this.currentPage--; this.fetchUsers(); } }, nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.fetchUsers(); } } }, created() { this.fetchUsers(); } }; </script> -
配置代理 在开发环境中配置代理,避免跨域问题。
// vue.config.js module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true } } } };
前后端联调
- 启动 SpringBoot 后端应用
- 启动 Vue 前端开发服务器
- 访问前端页面,测试分页功能是否正常工作
注意事项
- 确保后端接口返回的数据格式与前端期望的一致
- 分页参数传递时注意页码的偏移量(后端通常从0开始,前端通常从1开始)
- 在生产环境中应移除宽松的跨域配置,改为精确的域名限制







