快速实现Springboot+Vue实现增删改查、分页查询、模糊查询功能
以下是一个简化的解决方案,展示了如何在Spring Boot后端和Vue前端之间实现基本的增删改查和分页查询功能。
Spring Boot后端:
- 引入依赖(
pom.xml
):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 实体类(
User.java
):
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 省略getter和setter
}
- Repository接口(
UserRepository.java
):
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findByNameContaining(String name, Pageable pageable);
}
- 控制器(
UserController.java
):
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public Page<User> list(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String name) {
Pageable pageable = PageRequest.of(page, size);
if (name == null) {
return userRepository.findAll(pageable);
} else {
return userRepository.findByNameContaining(name, pageable);
}
}
@PostMapping
public User create(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userRepository.save(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
Vue前端:
- 安装依赖(
package.json
):
{
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-router": "^3.2.0"
}
}
- 列表页面(
Users.vue
):
<template>
<div>
<input v-model="search" placeholder="Search...">
评论已关闭