文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

怎么搭建SpringBoot+Vue前后端分离

2023-07-05 19:27

关注

本文小编为大家详细介绍“怎么搭建SpringBoot+Vue前后端分离”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么搭建SpringBoot+Vue前后端分离”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1 什么是前后端分离

前后端分离是目前互联网开发中比较广泛使用的开发模式,主要是将前端和后端的项目业务进行分离,可以做到更好的解耦合,前后端之间的交互通过xml或json的方式,前端主要做用户界面的渲染,后端主要负责业务逻辑和数据的处理。

怎么搭建SpringBoot+Vue前后端分离

2 Spring Boot后端搭建

2.1 Mapper层

请参阅这篇文章 手把手教你SpringBoot整合Mybatis

此次项目的后端搭建就是在这个项目的基础上

2.2 Service层

接口:

public interface StudentService {        public int saveStudent(Student student);        public Student findStudentById(Integer id);        public List<Student> findAllStudent();        public int removeStudentById(Integer id);        public int updateStudentById(Student student);}

实现类:

@Servicepublic class StudentServiceImpl implements StudentService {    @Autowired    private XmlStudentMapper xmlStudentMapper;    @Override    public int saveStudent(Student student) {        return xmlStudentMapper.saveStudent(student);    }    @Override    public Student findStudentById(Integer id) {        return xmlStudentMapper.findStudentById(id);    }    @Override    public List<Student> findAllStudent() {        return xmlStudentMapper.findAllStudent();    }    @Override    public int removeStudentById(Integer id) {        return xmlStudentMapper.removeStudentById(id);    }    @Override    public int updateStudentById(Student student) {        return xmlStudentMapper.updateStudentById(student);    }}

2.3 Controller层

@RestController@RequestMapping("/student")public class StudentController {    @Autowired    private StudentService studentService;        @PostMapping("/save")    public int saveStudent(@RequestBody Student student) {        int result;        try {            result = studentService.saveStudent(student);        } catch (Exception exception) {            return -1;        }        return result;    }        @GetMapping("/findAll")    public List<Student> findAll() {        return studentService.findAllStudent();    }        @GetMapping("/findById/{id}")    public Student findById(@PathVariable("id") Integer id) {        return studentService.findStudentById(id);    }        @DeleteMapping("/remove/{id}")    public int remove(@PathVariable("id") Integer id) {        return studentService.removeStudentById(id);    }        @PostMapping("/update")    public int update(@RequestBody Student student) {        return studentService.updateStudentById(student);    }}

2.4 配置类

解决跨域请求

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

图解跨域问题:

怎么搭建SpringBoot+Vue前后端分离

3 Vue前端搭建

3.1 新建Vue_cli2.x项目

3.2 引入路由

npm install vue-router --save

3.3 新建文件

怎么搭建SpringBoot+Vue前后端分离

3.4 配置和测试路由

main.js配置

import Vue from 'vue'import App from './App.vue'import router from './router'Vue.config.productionTip = falsenew Vue({    render: h => h(App),    router}).$mount('#app')

index.js

//注册路由import Vue from 'vue';import VueRouter from 'vue-router';//引入路由import index from '../view/index'import update from "../view/update";import selectAll from "../view/selectAll";import selectOne from "../view/selectOne";import insert from "../view/insert";Vue.use(VueRouter);const router = new VueRouter({    routes: [        {            name: "主页重定向",            path: "/",            redirect: "/index"        }, {            name: "主页",            path: "/index",            component: index,            children: [                {                    name: "修改操作",                    path: "/update",                    component: update,                }, {                    name: "查看全部",                    path: "/selectAll",                    component: selectAll,                }, {                    name: "查看一个",                    path: "/selectOne",                    component: selectOne,                }, {                    name: "添加一个",                    path: "/insert",                    component: insert,                }            ]        }    ]})export default router

App.vue

<template>    <div id="app">        <router-view/>    </div></template><script>export default {    name: 'App',}</script>

index.vue

<template>    <div>        <router-link to="update">update</router-link>        <br>        <router-link to="selectAll"> selectAll</router-link>        <br>        <router-link to="selectOne"> selectOne</router-link>        <br>        <router-link to="insert"> insert</router-link>        <br>        <br>        <router-view></router-view>    </div></template><script>export default {    name: "index"}</script><style scoped></style>

insert.vue

<template>    <div>        insert    </div></template><script>export default {    name: "insert"}</script><style scoped></style>

selectOne.vue

<template>    <div>        selectOne    </div></template><script>export default {    name: "selectOne"}</script><style scoped></style>

selectAll.vue

<template>    <div>        selectAll    </div></template><script>export default {    name: "selectAll"}</script><style scoped></style>

update.vue

<template>    <div>        update    </div></template><script>export default {    name: "update"}</script><style scoped></style>

测试

启动项目

npm run serve

访问:http://localhost:8080/

怎么搭建SpringBoot+Vue前后端分离

点击相关标签时会显示响应页面

3.5 引入Element UI

npm i element-ui -S

main.js

import Vue from 'vue'import App from './App.vue'import router from './router'import ElementUI from 'element-ui'import 'element-ui/lib/theme-chalk/index.css'Vue.config.productionTip = falseVue.use(ElementUI)new Vue({    render: h => h(App),    router}).$mount('#app')

3.6 使用Element UI美化页面

index.vue

<template>    <div>        <el-menu class="el-menu-demo" mode="horizontal" :router="true">            <el-menu-item index="/selectAll">全部学生</el-menu-item>            <el-menu-item index="/insert">添加学生</el-menu-item>            <el-menu-item index="/selectOne">查看学生</el-menu-item>            <el-menu-item index="/update">修改学生</el-menu-item>        </el-menu>        <router-view></router-view>    </div></template><script>export default {    name: "index"}</script><style scoped></style>

insert.vue

<template>    <div>        <el-form :model="ruleForm" status-icon  label-width="100px" class="demo-ruleForm" >            <el-form-item label="姓名" prop="pass">                <el-input type="text" v-model="ruleForm.name" ></el-input>            </el-form-item>            <el-form-item label="年龄" prop="checkPass">                <el-input type="text" v-model="ruleForm.age" ></el-input>            </el-form-item>            <el-form-item>                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>            </el-form-item>        </el-form>    </div></template><script>export default {    name: "insert",    data() {        return {            ruleForm: {                name: '',                age: ''            }        };    },    methods: {        submitForm(formName) {            this.$refs[formName].validate((valid) => {                if (valid) {                    alert('submit!');                } else {                    console.log('error submit!!');                    return false;                }            });        },    }}</script><style scoped></style>

selectOne.vue

<template>    <div>        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"                 >            <el-form-item label="ID" prop="pass">                <el-input type="text" v-model="ruleForm.id"></el-input>            </el-form-item>            <el-form-item label="姓名" prop="pass">                <el-input type="text" v-model="ruleForm.name"></el-input>            </el-form-item>            <el-form-item label="年龄" prop="checkPass">                <el-input type="text" v-model="ruleForm.age"></el-input>            </el-form-item>            <el-form-item>                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>                <el-button @click="resetForm('ruleForm')">重置</el-button>            </el-form-item>        </el-form>    </div></template><script>export default {    name: "selectOne",    data() {        return {            ruleForm: {                id: '',                name: '',                age: ''            }        };    },    methods: {        submitForm(formName) {            this.$refs[formName].validate((valid) => {                if (valid) {                    alert('submit!');                } else {                    console.log('error submit!!');                    return false;                }            });        },        resetForm(formName) {            this.$refs[formName].resetFields();        }    }}</script><style scoped></style>

selectAll.vue

<template>    <div>        <template>            <el-table                  :data="tableData"                  >                <el-table-column                      prop="id"                      label="ID"                      width="180">                </el-table-column>                <el-table-column                      prop="name"                      label="姓名"                      width="180">                </el-table-column>                <el-table-column                      prop="age"                      label="年龄">                </el-table-column>                <el-table-column                      label="操作">                    <template>                        <el-button type="warning" size="small">修改</el-button>                        <el-button type="danger" size="small">删除</el-button>                    </template>                </el-table-column>            </el-table>        </template>    </div></template><script>export default {    name: "selectAll",    data() {        return {            tableData: []        }    }}</script><style scoped></style>

update.vue

<template>    <div>        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"                 >            <el-form-item label="ID" prop="pass">                <el-input type="text" v-model="ruleForm.id"></el-input>            </el-form-item>            <el-form-item label="姓名" prop="checkPass">                <el-input type="text" v-model="ruleForm.name"></el-input>            </el-form-item>            <el-form-item label="年龄" prop="age">                <el-input type="text" v-model="ruleForm.age"></el-input>            </el-form-item>            <el-form-item>                <el-button type="warning" @click="submitForm('ruleForm')">修改</el-button>            </el-form-item>        </el-form>    </div></template><script>export default {    name: "update",    data() {        return {            ruleForm: {                id: '',                name: '',                age: ''            }        };    },    methods: {        submitForm(formName) {            this.$refs[formName].validate((valid) => {                if (valid) {                    alert('submit!');                } else {                    console.log('error submit!!');                    return false;                }            });        },        resetForm(formName) {            this.$refs[formName].resetFields();        }    }}</script><style scoped></style>

效果

怎么搭建SpringBoot+Vue前后端分离

怎么搭建SpringBoot+Vue前后端分离

3.7 整合axios与Spring Boot后端交互

npm install axios --save

insert.vue

<template>    <div>        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"                 >            <el-form-item label="姓名" prop="pass">                <el-input type="text" v-model="ruleForm.name"></el-input>            </el-form-item>            <el-form-item label="年龄" prop="checkPass">                <el-input type="text" v-model="ruleForm.age"></el-input>            </el-form-item>            <el-form-item>                <el-button type="primary" @click="submitForm()">提交</el-button>            </el-form-item>        </el-form>    </div></template><script>import axios from 'axios'export default {    name: "insert",    data() {        return {            ruleForm: {                name: '',                age: ''            }        };    },    methods: {        submitForm() {            axios.post("http://localhost:8081/student/save", this.ruleForm).then(function (resp) {                console.log(resp)            })        },    }}</script><style scoped></style>

selectOne.vue

<template>    <div>        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"                 >            <el-form-item label="ID" prop="pass">                <el-input type="text" v-model="ruleForm.id"></el-input>            </el-form-item>            <el-form-item label="姓名" prop="pass">                <el-input type="text" v-model="ruleForm.name"></el-input>            </el-form-item>            <el-form-item label="年龄" prop="checkPass">                <el-input type="text" v-model="ruleForm.age"></el-input>            </el-form-item>        </el-form>    </div></template><script>import axios from "axios";export default {    name: "selectOne",    data() {        return {            ruleForm: {                id: '',                name: '',                age: ''            }        };    },    methods: {        getStudent() {            const _this = this;            axios.get("http://localhost:8081/student/findById/" + this.$route.query.id).then(function (resp) {                _this.ruleForm = resp.data;            })        }    },    created() {        this.getStudent();    }}</script><style scoped></style>

selectAll.vue

<template>    <div>        <template>            <el-table                  :data="tableData"                  >                <el-table-column                      prop="id"                      label="ID"                      width="180">                </el-table-column>                <el-table-column                      prop="name"                      label="姓名"                      width="180">                </el-table-column>                <el-table-column                      prop="age"                      label="年龄">                </el-table-column>                <el-table-column                      label="操作">                    <template slot-scope="scope">                        <el-button type="primary" size="small" @click="select(scope.row)">查看</el-button>                        <el-button type="warning" size="small" @click="update(scope.row)">修改</el-button>                        <el-button type="danger" size="small" @click="remove(scope.row)">删除</el-button>                    </template>                </el-table-column>            </el-table>        </template>    </div></template><script>import axios from "axios";export default {    name: "selectAll",    data() {        return {            tableData: []        }    },    methods: {        getData() {            const _this = this;            axios.get("http://localhost:8081/student/findAll").then(function (resp) {                _this.tableData = resp.data;            })        },        remove(stu) {            const _this = this;            if (confirm("确定删除吗?")) {                axios.delete("http://localhost:8081/student/remove/" + stu.id).then(function (resp) {                    if (resp.data == 1) {                        _this.getData();                    }                })            }        },        select(stu) {            this.$router.push({                path: "/selectOne",                query:{                    id: stu.id                }            })        },        update(stu) {            this.$router.push({                path: "/update",                query:{                    id: stu.id                }            })        }    },    created() {        this.getData();    }}</script><style scoped></style>

update.vue

<template>    <div>        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm"                 >            <el-form-item label="ID">                <el-input type="text" v-model="ruleForm.id" disabled></el-input>            </el-form-item>            <el-form-item label="姓名">                <el-input type="text" v-model="ruleForm.name"></el-input>            </el-form-item>            <el-form-item label="年龄">                <el-input type="text" v-model="ruleForm.age"></el-input>            </el-form-item>            <el-form-item>                <el-button type="warning" @click="submitForm()">修改</el-button>            </el-form-item>        </el-form>    </div></template><script>import axios from "axios";export default {    name: "update",    data() {        return {            ruleForm: {                id: '',                name: '',                age: ''            }        };    },    methods: {        submitForm() {            axios.post("http://localhost:8081/student/update", this.ruleForm).then(function (resp) {                console.log(resp)            })        },        getStudent() {            const _this = this;            axios.get("http://localhost:8081/student/findById/" + this.$route.query.id).then(function (resp) {                _this.ruleForm = resp.data;            })        }    },    created() {        this.getStudent();    }}</script><style scoped></style>

读到这里,这篇“怎么搭建SpringBoot+Vue前后端分离”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯