在Vue中调用SpringBoot接口需要先建立Vue项目,并添加axios库用于发起请求。然后在Vue中编写前端页面,调用SpringBoot接口。
以下是一个示例代码,前端页面需要调用后端接口,实现通过Vue显示SpringBoot后端数据。
在Vue中安装axios库:
npm install axios --save
Vue中编写前端页面代码:
- <template>
- <div>
- <h2>员工列表</h2>
- <table>
- <thead>
- <tr>
- <th>员工ID</th>
- <th>员工姓名</th>
- <th>员工部门</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="employee in employees" :key="employee.id">
- <td>{{ employee.id }}</td>
- <td>{{ employee.name }}</td>
- <td>{{ employee.department }}</td>
- </tr>
- </tbody>
- </table>
- </div>
- </template>
-
- <script>
- import axios from "axios";
-
- export default {
- name: "EmployeeList",
- data() {
- return {
- employees: [],
- };
- },
- created() {
- this.getEmployees();
- },
- methods: {
- getEmployees() {
- axios.get("http://localhost:8080/api/employees").then((response) => {
- this.employees = response.data;
- });
- },
- },
- };
- </script>
在SpringBoot中编写接口代码:
- @RestController
- @RequestMapping("/api")
- public class EmployeeController {
- @Autowired
- private EmployeeRepository employeeRepository;
-
- @GetMapping("/employees")
- public List
getAllEmployees() { - return employeeRepository.findAll();
- }
- }
在SpringBoot中添加依赖库:
xml
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
这就是一个简单的Vue对接SpringBoot接口的完整代码。