Vue3 + Axios + SpringBoot 请求实现指南

作为一名经验丰富的开发者,我将向你介绍如何在 Vue3 中使用 Axios 发送请求到 SpringBoot 服务。以下是整个流程的步骤和代码示例。

步骤流程

以下是实现 Vue3 + Axios + SpringBoot 请求的步骤:

步骤描述
1安装 Axios
2创建 Vue3 组件
3在 Vue3 组件中使用 Axios 发送请求
4在 SpringBoot 中创建控制器和方法
5测试请求

代码实现

1. 安装 Axios

在 Vue3 项目中,首先需要安装 Axios:

npm install axios
  • 1.
2. 创建 Vue3 组件

创建一个 Vue3 组件,例如 HelloWorld.vue

<template>
  <div>
    {{ message }}
    <button @click="fetchData">Fetch Data</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      message: ''
    };
  },
  methods: {
    fetchData() {
      axios.get('http://localhost:8080/api/data')
        .then(response => {
          this.message = response.data;
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    }
  }
};
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • <template> 标签定义了组件的 HTML 结构。
  • <script> 标签中导入了 Axios,并定义了组件的数据和方法。
  • fetchData 方法使用 Axios 发送 GET 请求到 SpringBoot 服务。
3. 在 SpringBoot 中创建控制器和方法

在 SpringBoot 项目中,创建一个控制器 DataController.java

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DataController {

  @GetMapping("/api/data")
  public String getData() {
    return "Hello from SpringBoot!";
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • @RestController 注解表示这是一个控制器类。
  • @GetMapping("/api/data") 注解表示处理 GET 请求,并映射到 /api/data 路径。
  • getData 方法返回一个字符串。
4. 测试请求

启动 SpringBoot 服务和 Vue3 应用,点击按钮发送请求,查看控制台输出。

5. 序列图

以下是请求的序列图:

SpringBoot Axios Vue3 SpringBoot Axios Vue3 发送 GET 请求 请求 /api/data 返回数据 处理响应

结尾

通过以上步骤,你已经学会了如何在 Vue3 中使用 Axios 发送请求到 SpringBoot 服务。希望这篇文章对你有所帮助。如果你有任何问题或需要进一步的帮助,请随时联系我。