SpringBoot+VUE实现前后端分离的实战记录

一,前端VUE项目

这里使用VUE UI创建一个VUE项目

命令行输入vue ui进入

D724A0CE-F517-4B0D-0410-122D23508A60.png

手动配置项目

4E98A813-1E16-7CEC-5A4D-EA1E45B36F42.png

选中这三个

269D632C-93F1-B7C5-0054-D865A4CD42F0.png

点击下一步->点击创建项目

用IDEA打开刚才创建的项目

IDEA中的安装vue插件并重启

F5D06D04-BB89-8C68-F5FE-89C9D1815A5A.png

IDEA控制台中输入vue add axios安装axios

84E1A649-5B58-9B1C-C9DF-B903704942F1.png

新建一个Show.vue

674D23BC-3905-6FB2-B897-5515405D373D.png

在index,js的routes中配置它的路由

0076668E-A39A-19C5-9636-4BE41824A80F.png

编写Show,vue向后端请求数据并展示

<template>
    <div>
        <table>
            <tr>
                <td>ID</td>
                <td>姓名</td>
                <td>性别</td>
            </tr>
            <tr v-for="user in users">
                <td>{{user.id}}</td>
                <td>{{user.name}}</td>
                <td>{{user.sex}}</td>
            </tr>
        </table>
    </div>
</template>
<script>
    export default {
        name: "Show",
        data(){
            return{
                users:[
                    {
                        id:"",
                        name:"",
                        sex:"",
                    }
                ]
            }
        },
        created() {
            const _this=this
            axios.get('http://localhost:8888/user/showAll').then(function (resp) {
                _this.users=resp.data
            })
        }
    }
</script>
<style scoped>
</style>
二,后端SpringBoot项目

编写一个查询功能

97F59356-EB87-62AC-017F-036CACD7FE54.png

controller层返回json数据

91D12939-E20F-40B8-7E12-B1E352456260.png

在spring boot中解决跨域问题

重写WebMvcConfigurer中的addCorsMappings()方法

@Configuration
public class CrosConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

后端测试(注意前后端端口号的区分,VUE占用了8080和8081,在Springboot中修改后端的端口号)

98F6E3B0-03AA-35DA-F9A7-1E4EAA15E034.png

数据输出成功

33D8EB2B-5976-A75C-2EB7-3393D4B0FD38.png

前端发请求拿数据

33260108-301D-2F46-15A0-74B0591BAB1B.png

前端拿数据成功!!!

FD88C144-7874-352F-E201-1CD831A8AEE3.png

收藏 (0)
评论列表
正在载入评论列表...
我是有底线的