Spring Boot结合Element UI前后端分离的aixos的简单操作
1:axios是什么?
- 基于promise用于浏览器和node.js的http客户端
- axios官网:http://www.axios-js.com/
2:准备工作:
- 安装axios:npm install axios
- 或者直接使用在线的cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- 我这边是结合了element UI来做的一个表格提交和查看与删除的数据
- 数据库创建表语句:
/* Navicat Premium Data Transfer Source Server : good Source Server Type : MySQL Source Server Version : 80019 Source Host : localhost:3306 Source Schema : xiaolu Target Server Type : MySQL Target Server Version : 80019 File Encoding : 65001 Date: 23/03/2021 20:20:18 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(0) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `birth` date NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
在springboot中创建数据库表的实体类 :
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private String sex; private String email; @JsonFormat(pattern = "yyyy-MM-dd") private Date birth; }
创建mapper接口:
@Mapper public interface UserMapper { /* 查找方法 */ List<User> finAll(); /* 添加方法 */ void adduser(User user); /* 删除方法 */ void delect(String id); }
编写对应的mapper.xml文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.kuang.Mapper.UserMapper"> <select id="finAll" resultType="User"> select id,name,sex,birth,email from user; </select> <insert id="adduser" parameterType="User"> insert into user values(#{id},#{name},#{sex},#{email},#{birth}); </insert> <delete id="delect" parameterType="String"> delete from user where id=#{id} </delete> </mapper>
再写server层:
public interface UserMapperImp { /* 查找方法 */ List<User> finAll(); /* 添加方法 */ void adduser(User user); /* 删除方法 */ void delect(String id); }
和实现类:
@Service @Transactional public class MyController implements UserMapperImp { @Autowired UserMapper userMapper; @Override public List<User> finAll() { return userMapper.finAll(); } @Override public void adduser(User user) { userMapper.adduser(user); } @Override public void delect(String id) { userMapper.delect(id); }}
这边在vo层写一个类来做个标记 用来查看方法是否成功:
@Data public class Result { private Boolean status=true; private String msg; }
最后写Controller层:
@CrossOrigin//解决跨域问题 @RestController //因为要解析为json public class UserController { @Autowired UserMapperImp userMapperImp; @RequestMapping("/user") public List<User> finAll(){ return userMapperImp.finAll(); } @PostMapping("/post") public Result testSave(@RequestBody User user){ Result result = new Result(); try { userMapperImp.adduser(user); result.setMsg("成功"); }catch (Exception e){ result.setStatus(false); result.setMsg("保存失败"); } return result; } @GetMapping("delect") public Result delect(String id){ Result result = new Result(); try { userMapperImp.delect(id); result.setMsg("成功"); }catch (Exception e){ result.setStatus(false); result.setMsg("保存失败"); } return result; }
这边springboot代码写好了
编写vue代码:
先创建一个vue项目 可以参考我的之前的element UI的第一个项目:
- Element UI的第一个程序(标签使用) - java小白名叫杰 - 博客园 https://www.cnblogs.com/yunjie0930/p/14563139.html
main.js配置中配置为一下代码:
import Vue from 'vue' import App from './App' import VueRouter from "vue-router"; import axios from 'axios' //扫描路由配置 import router from "./router" //导入elementUI import ElementUI from "element-ui" //导入element css import 'element-ui/lib/theme-chalk/index.css' //使用 Vue.prototype.$http= axios Vue.use(VueRouter) Vue.use(ElementUI) Vue.config.productionTip = false new Vue({ el: '#app', router, render: h => h(App),//ElementUI规定这样使用 })
App.vue:这边这样写是为了让页面都有这个配置:
<template> <div id="app"> <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"> <el-menu-item index="1">主页</el-menu-item> <el-menu-item index="2"> <a href="#/index">员工</a> </el-menu-item> <el-menu-item index="3">登录主页</el-menu-item> <el-menu-item index="4"><a href="https://www.ele.me" target="_blank">订单管理</a></el-menu-item> </el-menu> <router-view></router-view> </div> </template> <script> export default { name: 'App', data() { return { activeIndex: '1', activeIndex2: '1' }; }, methods: { handleSelect(key, keyPath) { console.log(key, keyPath); } } } </script> <style> .el-menu-demo{ } </style>
效果图:
注册路由:因为我的文件名叫Add.vue和Index.vue:
//导入vue import Vue from 'vue'; import VueRouter from 'vue-router'; //导入组件 import Index from '../components/Index' import Add from '../components/Add' //使用 Vue.use(VueRouter); //导出 export default new VueRouter({ routes: [ {path: '/index',component: Index}, {path: '/add',component: Add} ] })
最后写出我们的Index.vue文件:
<template> <div> <el-table :data="tableData" style="width: 100%"> <el-table-column label="ID" width="180"> <template slot-scope="scope"> <i class="el-icon-time"></i> <span style="margin-left: 10px">{{ scope.row.id }}</span> </template> </el-table-column> <el-table-column label="姓名" width="180"> <template slot-scope="scope"> <el-popover trigger="hover" placement="top"> <p>姓名: {{ scope.row.name }}</p> <p>邮箱: {{ scope.row.email}}</p> <div slot="reference" class="name-wrapper"> <el-tag size="medium">{{ scope.row.name }}</el-tag> </div> </el-popover> </template> </el-table-column> <el-table-column label="生日" prop="birth"></el-table-column> <el-table-column label="性别" prop="sex"></el-table-column> <el-table-column label="操作" > <template slot-scope="scope"> <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-button type="success" round style="margin-top:10px "><a href="#/add">添加</a></el-button> </div> </template> <script> export default { name: "Index", data() { return { tableData: [ ],
//对应数据库的字段 form: { birth:'', sex:'男', name: '', email:'' } } },
//方法 methods: { handleEdit(index, row) { form=this.form },
//删除按钮绑定的方法 然后用判断下标id来从后端的方法删除此数据 handleDelete(index, row) { this.$http.get("http://localhost:8081/delect?id="+row.id).then(res=>{
//res.data.status是后端自定义的标记类 如果为ture则打印成功 if (res.data.status){ console.log(res.msg); }else { console.log(res.msg); } }) } },
//展示数据 从后端获取数据 然后赋值给data来展示 created() { this.$http.get("http://localhost:8081/user").then(res=> { this.tableData=res.data; }); }} </script> <style scoped> </style>
显示情况:
编写表单Add.vue文件:
<template> <el-form ref="form" :model="form" label-width="80px"> <el-form-item label="姓名"> <el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label="生日"> <el-col :span="11"> <el-date-picker type="date" placeholder="选择日期" v-model="form.birth" style="width: 100%;"></el-date-picker> </el-col> <el-col class="line" :span="2">-</el-col> </el-form-item> <el-form-item label="性别"> <el-radio-group v-model="form.sex"> <el-radio label="男"></el-radio> <el-radio label="女"></el-radio> </el-radio-group> </el-form-item> <el-form-item label="活动形式"> <el-input type="textarea" v-model="form.email"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">添加</el-button> <el-button>取消</el-button> </el-form-item> </el-form> </template> <script> export default { name: "Add",
//data里面的数据表单对应数据库的字段 data() { return { form: { name: '', birth:'', sex:'男', email:'' } } }, methods: {
//添加数据的方法 使用post onSubmit() {
this.$http.post("http://localhost:8081/post",this.form).then(res=> {
//判断状态 状态为ture则成功 并把表单清空 if (res.data.status) { console.log(res.data), this.form = {} } else {
//为false则失败 打印失败信息 console.log(res.data.status) } }) } } } </script> <style scoped> </style>
运行图:
展示图:
记录一下成长过程 加油!!!