Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue和springboot的前后端交互

作者:缺爱╮不缺钙   发布日期:2026-01-11   浏览:22

// 后端代码 (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>

解释说明

  1. 后端部分 (Spring Boot):

    • @RestController@RequestMapping("/api") 定义了一个 RESTful API 控制器,处理 /api 路径下的请求。
    • @GetMapping("/users") 定义了一个 GET 请求处理器,用于获取所有用户的数据。
    • User 类是一个简单的 Java Bean,包含用户的 ID 和名字。
  2. 前端部分 (Vue.js):

    • 使用了 Vue 的单文件组件(SFC)格式。
    • data() 方法返回一个对象,其中包含 users 数组,用于存储从后端获取的用户数据。
    • created() 生命周期钩子在组件创建时调用 fetchUsers 方法,以获取用户数据。
    • fetchUsers 方法使用 axios 库发送 HTTP GET 请求到后端 API,并将响应数据赋值给 users 数组。
    • 模板部分使用 v-for 指令遍历 users 数组并显示每个用户的名字。

上一篇:vue 点击事件

下一篇:vue 事件

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

vue3组件传值的方式

vue3 子路由

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站