SpringBoot和Vue 实现增删改查、分页查询、模糊查询
以下是一个简化的示例,展示了如何在Spring Boot后端和Vue前端之间实现增删改查、分页查询和模糊查询。
后端(Spring Boot):
// Controller
@RestController
@RequestMapping("/api/items")
public class ItemController {
@Autowired
private ItemService itemService;
// 增加
@PostMapping
public ResponseEntity<Item> createItem(@RequestBody Item item) {
return ResponseEntity.ok(itemService.createItem(item));
}
// 查询所有(分页)
@GetMapping
public ResponseEntity<Page<Item>> getItems(@PageableDefault(size = 10, page = 0) Pageable pageable) {
return ResponseEntity.ok(itemService.getItems(pageable));
}
// 查询单个
@GetMapping("/{id}")
public ResponseEntity<Item> getItemById(@PathVariable("id") Long id) {
return ResponseEntity.ok(itemService.getItemById(id).orElseThrow(() -> new ItemNotFoundException(id)));
}
// 修改
@PutMapping("/{id}")
public ResponseEntity<Item> updateItem(@PathVariable("id") Long id, @RequestBody Item item) {
return ResponseEntity.ok(itemService.updateItem(id, item));
}
// 删除
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteItem(@PathVariable("id") Long id) {
itemService.deleteItemById(id);
return ResponseEntity.noContent().build();
}
// 模糊查询
@GetMapping("/search/{keyword}")
public ResponseEntity<List<Item>> searchItems(@PathVariable("keyword") String keyword) {
return ResponseEntity.ok(itemService.searchItems(keyword));
}
}
// Service
public interface ItemService {
Item createItem(Item item);
Page<Item> getItems(Pageable pageable);
Optional<Item> getItemById(Long id);
Item updateItem(Long id, Item item);
void deleteItemById(Long id);
List<Item> searchItems(String keyword);
}
// Entity
public class Item {
private Long id;
private String name;
// ... 其他字段和方法
}
前端(Vue.js):
<template>
<!-- 添加、编辑表单 -->
</template>
<script>
export default {
// ...
methods: {
// 获取列表
fetchItems(page) {
this.$http.get('/api/items?page=' + page)
.then(response => {
评论已关闭