// 后端代码 (Spring Boot)
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
// 模拟从数据库获取用户数据
List<User> users = Arrays.asList(
new User(1L, "Alice"),
new User(2L, "Bob"),
new User(3L, "Charlie")
);
return ResponseEntity.ok(users);
}
// 用户类
static class User {
private Long id;
private String name;
public User(Long id, String name) {
this.id = id;
this.name = name;
}
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
// 前端代码 (Vue.js)
<template>
<div>
<h1>User List</h1>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
users: []
};
},
created() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
try {
const response = await axios.get('http://localhost:8080/api/users');
this.users = response.data;
} catch (error) {
console.error('There was an error fetching the users!', error);
}
}
}
};
</script>
后端部分 (Spring Boot):
@RestController 和 @RequestMapping("/api") 定义了一个 RESTful API 控制器,处理 /api 路径下的请求。@GetMapping("/users") 定义了一个 GET 请求处理器,用于获取所有用户的数据。User 类是一个简单的 Java Bean,包含用户的 ID 和名字。前端部分 (Vue.js):
data() 方法返回一个对象,其中包含 users 数组,用于存储从后端获取的用户数据。created() 生命周期钩子在组件创建时调用 fetchUsers 方法,以获取用户数据。fetchUsers 方法使用 axios 库发送 HTTP GET 请求到后端 API,并将响应数据赋值给 users 数组。v-for 指令遍历 users 数组并显示每个用户的名字。上一篇:vue 点击事件
下一篇:vue 事件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站