vue3+ajax springboot 增删查
时间: 2023-10-25 07:08:08 浏览: 94
Vue3是一个流行的JavaScript框架,用于构建现代化的单页面应用程序。Spring Boot是一个流行的Java框架,用于构建Web应用程序。Ajax是一种Web开发技术,用于异步地向服务器发送HTTP请求。
在Vue3中使用Ajax与Spring Boot进行增删查操作,可以按照以下步骤进行:
1. 在Vue3中安装axios库,用于发送Ajax请求。
```
npm install axios
```
2. 在Vue3中定义数据模型和方法。
```
<template>
<div>
<h1>学生列表</h1>
<ul>
<li v-for="student in students" :key="student.id">{{ student.name }} - {{ student.age }}</li>
</ul>
<h1>添加学生</h1>
<form @submit.prevent="addStudent">
<label>
姓名:
<input type="text" v-model="newStudent.name">
</label>
<label>
年龄:
<input type="number" v-model="newStudent.age">
</label>
<button type="submit">添加</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
students: [],
newStudent: {
name: '',
age: ''
}
};
},
methods: {
getStudents() {
axios.get('/api/students').then(response => {
this.students = response.data;
});
},
addStudent() {
axios.post('/api/students', this.newStudent).then(() => {
this.newStudent.name = '';
this.newStudent.age = '';
this.getStudents();
});
}
},
mounted() {
this.getStudents();
}
};
</script>
```
3. 在Spring Boot中定义控制器和服务。
```
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public List<Student> getStudents() {
return studentService.getStudents();
}
@PostMapping
public void addStudent(@RequestBody Student student) {
studentService.addStudent(student);
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
}
@GetMapping("/{id}")
public Student getStudentById(@PathVariable Long id) {
return studentService.getStudentById(id);
}
@PutMapping("/{id}")
public void updateStudent(@PathVariable Long id, @RequestBody Student student) {
studentService.updateStudent(id, student);
}
}
@Service
public class StudentService {
private List<Student> students = new ArrayList<>();
public List<Student> getStudents() {
return students;
}
public void addStudent(Student student) {
students.add(student);
}
public void deleteStudent(Long id) {
students.removeIf(student -> student.getId().equals(id));
}
public Student getStudentById(Long id) {
return students.stream().filter(student -> student.getId().equals(id)).findFirst().orElse(null);
}
public void updateStudent(Long id, Student student) {
Student oldStudent = getStudentById(id);
oldStudent.setName(student.getName());
oldStudent.setAge(student.getAge());
}
}
public class Student {
private Long id;
private String name;
private Integer age;
public Student(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
// getters and setters
}
```
4. 在Spring Boot中定义数据存储。
可以使用内存存储(如上例中的List)或者使用数据库存储(如MySQL、PostgreSQL等)。
5. 运行Vue3应用程序和Spring Boot应用程序。
通过命令行运行Vue3应用程序:
```
npm run serve
```
通过IDE或命令行运行Spring Boot应用程序:
```
mvn spring-boot:run
```
然后就可以在浏览器中访问Vue3应用程序,并进行增删查操作了。
阅读全文