利用pagehelper PageInfo组件 ,手动实现分页
时间: 2023-07-25 14:17:23 浏览: 185
PageHelper是一个优秀的分页插件,可以快速实现分页功能。而PageInfo是PageHelper中用于封装分页信息的类,可以方便地获取分页相关的信息,比如当前页码、总页数、总记录数等。下面是一个基于PageHelper和PageInfo实现分页的示例代码:
1. 首先,在pom.xml中添加PageHelper依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.1</version>
</dependency>
```
2. 在需要进行分页的Mapper方法中添加分页参数:
```java
public interface UserMapper {
List<User> selectAllUsers();
List<User> selectUsersByPage(@Param("start") int start, @Param("pageSize") int pageSize);
}
```
3. 在DAO层中进行分页操作:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> getUsersByPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.selectAllUsers();
return new PageInfo<>(userList);
}
}
```
4. 在Controller中获取分页数据:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public PageInfo<User> getUsersByPage(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
return userService.getUsersByPage(pageNum, pageSize);
}
}
```
5. 在前端页面中使用PageInfo组件进行分页:
```html
<ul>
<li v-for="user in userList" :key="user.id">{{ user.name }}</li>
</ul>
<PageInfo :page-info="pageInfo" @page-change="handlePageChange" />
```
```js
import PageInfo from 'vue-pageinfo'
export default {
components: {
PageInfo
},
data() {
return {
userList: [], // 当前页的用户列表
pageInfo: null // 分页信息
}
},
mounted() {
this.getUserList()
},
methods: {
getUserList() {
axios.get('/users', {
params: {
pageNum: this.pageInfo ? this.pageInfo.pageNum : 1,
pageSize: this.pageInfo ? this.pageInfo.pageSize : 10
}
}).then(response => {
this.userList = response.data.list
this.pageInfo = response.data
})
},
handlePageChange(page) {
// 处理页码改变事件
this.pageInfo.pageNum = page
this.getUserList()
}
}
}
```
希望这个示例能够帮助到您!
阅读全文