Springboot3+vue3来实现分页查询

安装axios 封装前后端

npm i axios -S

跨域处理

(浏览器不能处理来自不同的两个地址)

在springboot里面统一处理跨域处理

package com.mmm.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@Configuration// 配置类
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

前端封装类

(这个超级好用,封装之后的res里面就只有里后端设定的result的格式 code,data,msg)

import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const request = axios.create({
  baseURL: 'http://localhost:9999',
  timeout: 30000  // 后台接口超时时间
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
request.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=utf-8';
  let user = JSON.parse(localStorage.getItem('code_user') || '{}')
  config.headers['token'] = user.token
  return config
}, error => {
  return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
  response => {
    let res = response.data;
    // 兼容服务端返回的字符串数据
    if (typeof res === 'string') {
      res = res ? JSON.parse(res) : res
    }
    if (res.code === '401') {
      ElMessage.error(res.msg)
      router.push('/login')
    } else {
      return res
    }
  },
  error => {
    if (error.response.status === 404) {
      ElMessage.error('未找到请求接口')
    } else if (error.response.status === 500) {
      ElMessage.error('系统异常,请查看后端控制台报错')
    } else {
      console.error(error.message)
    }
    return Promise.reject(error)
  }
)

export default reques

发起一次请求

request.get('admin/selectAll').then(res=>{
  if(res.code ==="200"){
    console.log(res)
    ElMessage.success(res.msg)
  }else{
    ElMessage.error(res.msg)
  }
})

分页查询

在pom.xml里面添加PageHelper依赖 引用的是·import com.github.pagehelper.PageInfo;

        <!-- 分页插件pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

<exclusion>其中这个标签是防止与本地的mybatis版本冲突注解了

后端

所以呢从后端写起

首先写controller层来接收前端的参数,传给service来使用方法和调用sql的接口方法,到mapper层 创建方法接口和mapper.xml来执行sql大概就是这个流程;

AdminController

@GetMapping("/selectPage")//全局唯一的
public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10")Integer pageSize,
                         Admin admin)  {
    PageInfo<Admin> PageInfo = adminService.selectPage(pageNum, pageSize, admin);
    return Result.success(PageInfo);

}

@RequestParam将数据json化, Admin admin接受admin类里面的属性 , adminService在前面创建了private AdminService adminservice的对象,调用里面的selectPage方法

AdminService

public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        // 开启分页功能
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }

将admin的属性传入selectAll的方法里

AdminMapper

public interface AdminMapper {
    List<Admin> selectAll(Admin admin);
}

AdminMapper.xml

   <select id="selectAll" resultType="com.mmm.entity.Admin">
        select * from `admin`
      <where>
          <if test="username!=null">username like concat('%',#{username},'%')</if>
          <if test="name!=null">and name like concat('%',#{name},'%')</if>
      </where>
        order by id desc
    </select>

使用where标签来实现动态查询,对于一个方法里面selectAll()里面可能没有值来传递,就在where标签添加判断如果为否就不实现

后端就over了;

前端

首先一些基本的查询框,表结构,分页器,

<div class="card" style="margin-bottom: 5px;">
  <el-input clearable @clear="load" style="width: 260px ;margin-right: 5px" v-model="data.username" placeholder="请输入账号查询" :prefix-icon="Search"></el-input>
  <el-input clearable @clear="load" style="width: 260px ;margin-right: 5px" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
  <el-button type="primary" icon="Search" @click="load">查询</el-button>
  <el-button type="warning" icon="RefreshRight" @click="reset">重置</el-button>
</div>

clearable 超级好用

来快速清除对话框的内容

对于两个绑定事件来

@click="load"@click="reset

const load =()=>{
  request.get('/admin/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      username:data.username,
      name:data.name,
    }
  }).then(res=>{
    if(res.code === '200'){
      data.tableData = res.data.list
      data.total = res.data.total

    }else {
      ElMessage.error(res.msg)
    }

  })
}
load()


const reset =()=>{
  data.name = null
  data.username = null
  load()
}

第一个加载load方法 用requet来请求后端并传入参数格式 request.get( 'url', {params:{ }}).then(res=>{

})

第二个重置reset方法 点击后 对话框里面的name,username的是赋值为空,重新全部加载

 <div class="card" style="margin-bottom: 5px;">
    <el-table :data="data.tableData" style=" width: 100%" :header-cell-style="{  color: '#333' ,backgroundColor: '#eaf4ff'}">
      <el-table-column type="select" width="55"/>
      <el-table-column prop="username" label="账号"/>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="email" label="邮箱"/>
    </el-table>
    </div>

表结构绑定表数据

const load =()=>{
  request.get('/admin/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      username:data.username,
      name:data.name,
    }
  }).then(res=>{
    if(res.code === '200'){
      data.tableData = res.data.list
      data.total = res.data.total

    }else {
      ElMessage.error(res.msg)
    }

  })
}
load()

data.tableData = res.data.list 在前端是数组表示,后端是list集合

分页器

<div class="card">
  <el-pagination
    v-model:current-page="data.pageNum"
    v-model:page-size="data.pageSize"
    layout="total,sizes, prev, pager, next,jumper"
    :page-sizes="[5,10,15]"
    :total="data.total"
    @current-change="load"
    @size-change="load"
    />
</div>

绑定的数据都在这里面,来显示在前端


const data = reactive({
  username: null,
  name: null,
  pageNum:1,
  pageSize:5,
  total:0,
  tableData: []

})
<think>好的,我现在需要帮助用户找到使用SpringBoot、MyBatisVue实现分页功能的示例代码教程。用户可能正在开发一个需要分页功能的Web应用,希望了解前后端如何配合实现这一功能。首先,我应该回顾用户提供的引用内容,看看里面有没有相关的配置或代码示例。 引用1提到了pagehelper组件在SpringBoot中的使用,引用了配置文件分页插件的设置。引用23都涉及到MyBatis Plus的分页配置,特别是引用3详细说明了如何配置MybatisPlusInterceptor并指定数据库类型。引用4则给出了SpringBoot的配置文件示例,包括数据源MyBatis的相关设置。这些引用内容主要集中在后端配置上,但用户还提到了Vue,所以需要整合前端部分。 接下来,我需要构建一个分步的解决方案,涵盖后端前端。后端部分应该包括SpringBoot整合MyBatis Plus的分页插件,创建控制器服务层来处理分页请求。前端部分需要Vue组件发送分页请求并处理响应数据,展示分页导航。 首先,后端配置方面,根据引用3的内容,配置MybatisPlusInterceptor并添加分页插件,指定数据库类型为MySQL。然后在服务层使用Page对象进行查询,控制器返回分页结果。引用2中的@MapperScan注解也是关键,确保Mapper接口被正确扫描。 前端部分,用户可能需要使用Vue发送GET请求,传递当前页每页大小的参数。使用axios进行HTTP通信,接收后端返回的分页数据,并在页面上展示列表分页控件。引用4中的端口号数据源配置也需要在后端配置文件中设置,确保前后端连接正确。 可能的问题包括分页插件的正确配置、前后端参数传递的一致性,以及Vue组件中处理分页事件的方法。需要确保后端返回的数据结构符合前端预期,比如包含记录列表、当前页、总页数等信息。此外,跨域问题也需要处理,可以在后端添加CORS配置。 最后,生成相关问题,帮助用户深入理解分页实现的各个方面,比如性能优化、异常处理、样式调整等。需要确保提供的代码示例正确,并符合用户的技术栈要求,比如MyBatis PlusVue的版本兼容性。</think>### SpringBoot+MyBatis+Vue分页实现方案 #### 一、后端实现SpringBoot+MyBatis Plus) 1. **添加依赖** ```xml <!-- pom.xml --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> ``` 2. **配置分页插件** ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } } ``` 3. **Service层实现** ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { public Page<User> getPage(int current, int size) { Page<User> page = new Page<>(current, size); return this.page(page); } } ``` 4. **Controller层接口** ```java @RestController @RequestMapping("/api/user") public class UserController { @Autowired private UserService userService; @GetMapping("/page") public Result<Page<User>> getPage(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size) { return Result.success(userService.getPage(current, size)); } } ``` #### 二、前端实现Vue3+Element Plus) 1. **分页组件** ```vue <template> <el-table :data="tableData"> <!-- 列定义 --> </el-table> <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total" @current-change="handlePageChange" /> </template> <script setup> import { ref, onMounted } from &#39;vue&#39; import axios from &#39;axios&#39; const currentPage = ref(1) const pageSize = ref(10) const total = ref(0) const tableData = ref([]) const loadData = async () => { const res = await axios.get(&#39;/api/user/page&#39;, { params: { current: currentPage.value, size: pageSize.value } }) tableData.value = res.data.records total.value = res.data.total } onMounted(loadData) const handlePageChange = (newPage) => { currentPage.value = newPage loadData() } </script> ``` #### 三、关键配置说明 1. **application.yml配置** ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/dbname?useSSL=false&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: map-underscore-to-camel-case: true ``` 2. **跨域配置(后端)** ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST"); } } ``` 该方案实现了以下功能特性: - 后端采用MyBatis Plus自动分页查询 - 前端使用Element Plus分页组件 - 支持动态页码切换 - 每页条数可配置化 - 自动处理分页参数映射
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值