VueSpringBootJava后端

SpringBoot+Vue前后端分离(CURD)Demo

2020-01-16  本文已影响0人  HeloWxl

我发现我好久没有更新了,写一篇证明我还活着。
既然是前后端分离的话,肯定是要有前端和后端的。
这里前端我使用的Vue+ElementUI,后端采用的是SpringBoot+Mybatis+Swagger2。
下面的话,我就做一个简单的Demo吧。
写的不好,请大家各位大佬们指点

1、后端

后端的话,我是使用之前基础上面改的。EasyCode(代码神器)

1.1 pom.xml

   <!--Swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.3</version>
        </dependency>

1.2 添加Swagger配置类

image.png
/**
 * Swagger2
 * 该项目访问地址:http://127.0.0.1:8089/doc.html
 * @author wangxl
 * @date 2019/8/16 20:19
 */
@Configuration
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.vue.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Vue接口测试")
                .description("简单优雅的restful风格")
                .termsOfServiceUrl("www.wangxianlin@icloud.com")
                .version("1.0")
                .build();
    }
}

1.3 添加注解

image.png

1.4 然后启动项目

浏览器输入网址:http://127.0.0.1:8089/doc.html

image.png

2、前端

前端,我使用的是Vue+ElementUi写的,界面简洁美观。

2.1 新建一个Vue项目

这里的话,我就不多说了,直接贴上一个链接:使用webstorm来创建并且运行vue项目详细教程

2.2 前端目录:

前端目录.png

2.3 页面与配置

2.3.1 配置

解决跨域问题:
Vue中解决跨域问题,请参照这篇文章:https://segmentfault.com/a/1190000011715088

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    // modeify
    proxyTable: {
      //modify
      '/api/**': {
        target: 'http://127.0.0.1:8089',//设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,//這裡true表示实现跨域
        pathRewrite: {
          '^/api': '/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
        }
      }
    },
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'

Vue.use(ElementUI)

axios.defaults.baseURL = 'http://localhost:8089/api'
// 将API方法绑定到全局
Vue.prototype.$axios = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

2.3.2 页面 table.vue

<template>
  <el-row>
    <el-col :span="24">
      <div class="grid-content">
        <el-container>
          <el-container>
            <!--导航部分-->
            <el-header>
              <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal">
                <el-menu-item index="1">用户信息列表</el-menu-item>
              </el-menu>
            </el-header>
            <!--表格-->
            <el-main>
              <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="id" label="ID" width="180"></el-table-column>
                <el-table-column prop="username" label="姓名" width="180"></el-table-column>
                <el-table-column prop="sex" label="性别"></el-table-column>
                <el-table-column prop="birthday" label="生日"></el-table-column>
                <el-table-column prop="address" label="家庭住址"></el-table-column>
                <el-table-column prop="password" label="密码"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      @click="editUser(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                      type="danger"
                      @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-main>
            <el-footer>
              <el-row>
                <el-button type="primary" @click="centerDialogVisible = true">添加</el-button>
              </el-row>
            </el-footer>
          </el-container>
        </el-container>
      </div>
      <!--      添加用户-->
      <el-dialog title="添加用户" :visible.sync="centerDialogVisible" :center="true" width="50%">
        <el-form :model="form">
          <el-form-item label="姓名:" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="生日:" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="请选择你的生日">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="性别:" :label-width="formLabelWidth">
            <el-select v-model="form.sex" placeholder="性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="家庭住址:" :label-width="formLabelWidth">
            <el-input v-model="form.address" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码:" :label-width="formLabelWidth">
            <el-input v-model="form.password" autocomplete="off" type="password"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" :center="true">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </div>
      </el-dialog>
      <!--      修改用户-->
      <el-dialog title="修改用户" :visible.sync="editformDialogVisible" :center="true" width="50%">
        <el-form :model="editform">
          <el-input v-model="editform.id" autocomplete="off" type="hidden" ></el-input>
          <el-form-item label="姓名:" :label-width="formLabelWidth">
            <el-input v-model="editform.name" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="性别:" :label-width="formLabelWidth">
            <el-select v-model="editform.sex" placeholder="性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生日:" :label-width="formLabelWidth">
          <el-date-picker
            v-model="editform.birthday"
            type="date"
            placeholder="请选择你的生日">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="家庭住址:" :label-width="formLabelWidth">
            <el-input v-model="editform.address" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码:" :label-width="formLabelWidth">
            <el-input v-model="editform.password" autocomplete="off" type="password"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" :center="true">
          <el-button @click="editformDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUser()">确 定</el-button>
        </div>
      </el-dialog>
    </el-col>
  </el-row>
</template>
<script>
  export default {
    data () {
      return {
        activeIndex: '1',
        // 表格内容
        tableData: [],
        centerDialogVisible: false,
        editformDialogVisible: false,
        //添加表单
        form: {
          name: '',
          sex: '',
          address: '',
          password: '',
          birthday:''
        },
        //修改表单
        editform: {
          id:'',
          name: '',
          sex: '',
          address: '',
          password: '',
          birthday:''
        },
        formLabelWidth: '80px'
      }
    },
    methods: {
      //添加用户
      addUser () {
        var _this = this
        _this.centerDialogVisible = false
        if (_this.form.name == '') {
          alert('姓名不能为空')
          return
        }
        if (_this.form.sex == '') {
          alert('请选择你的性别')
          return
        }
        if (_this.form.birthday == '') {
          alert('请选择你的生日')
          return
        }
        if (_this.form.address == '') {
          alert('请填写你的家庭住址')
          return
        }
        if (_this.form.password == '') {
          alert('密码不能为空')
          return
        }
        let user = JSON.stringify({
          username: _this.form.name,
          sex: _this.form.sex,
          address: _this.form.address,
          password: _this.form.password,
          birthday:_this.form.birthday
        })
        _this.$axios.post('/api/user/insertUser', user, {
          headers: {
            'Content-Type': 'application/json;charset=utf-8'  //头部信息
          }
        }).then(res => {
            if (res.data == 1) {
              _this.$message({
                message: '添加成功',
                type: 'success'
              })
              //刷新页面
              this.getData()
            }
          }
        ).catch(error => {
          _this.$message.error('添加失败,服务其内部错误')
        })
      },
      //修改用户弹窗 赋值操作
      editUser (index, row) {
        var _this = this;
        _this.editformDialogVisible=true;
        _this.editform.id = row.id;
        _this.editform.name = row.username;
        _this.editform.sex = row.sex;
        _this.editform.address = row.address;
        _this.editform.password = row.password;
        _this.editform.birthday = row.birthday;
      },
      //修改用户
      updateUser(){
        var _this = this;
        _this.editformDialogVisible=false;
        if (_this.editform.name == '') {
          alert('姓名不能为空')
          return
        }
        if (_this.editform.sex == '') {
          alert('请选择你的性别')
          return
        }
        if (_this.editform.birthday == '') {
          alert('请选择你的生日')
          return
        }
        if (_this.editform.address == '') {
          alert('请填写你的家庭住址')
          return
        }
        if (_this.editform.password == '') {
          alert('密码不能为空')
          return
        }
        let user = JSON.stringify({
          id:_this.editform.id,
          username: _this.editform.name,
          sex: _this.editform.sex,
          address: _this.editform.address,
          password: _this.editform.password,
          birthday:_this.editform.birthday
        })
        _this.$axios.post('/user/updateUser', user, {
          headers: {
            'Content-Type': 'application/json;charset=utf-8'  //头部信息
          }
        }).then(res => {
            if (res.data == 1) {
              _this.$message({
                message: '修改成功',
                type: 'success'
              })
              //刷新页面
              this.getData()
            }
          }
        ).catch(error => {
          _this.$message.error('修改失败,服务其内部错误')
          console.log(error)
        })

      },
      //删除用户
      deleteUser (index, row) {
        // index 表示当前所在行的行号
        // row  表示当前所在行的数据
        this.$confirm('是否删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var _this = this
          _this.$axios.get('/user/deleteUserById', {
            params: {
              id: row.id
            }
          }).then(res => {
              if (res.data == 1) {
                _this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                //刷新页面
                this.getData()
              }
            }
          ).catch(error => {
            _this.$message.error('删除失败,服务其内部错误')
            console.log(error)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      getData () {
        var _this = this
        _this.$axios.get('/user/quertUser', {
            params: {
              offset: 0,
              limit: 10
            }
          }
        ).then(res => {
            this.tableData = res.data
          }
        ).catch(error => {
          console.log(error)
        })
      }
    },
    mounted () {         //mounted:渲染HTML成功后调 用getData方法读取商品数据,getBrandsData读取品牌数据
      this.getData()
    }
  }
</script>
<style scoped>
</style>

3、测试

上一篇下一篇

猜你喜欢

热点阅读