Vue与Springboot的简单整合

Vue与Springboot的简单整合

概述:本文主要讲述vue+springboot JPA实现登录注册的方法,其中首页和登录效果如图所示:

Vue与Springboot的简单整合

1、安装node和npm

安装方法参考官网

2、安装vue和vue-cli

(1)方式一

npm install vue
npm install vue-cli -g

(2)方式二:使用使用淘宝镜像安装

npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install cnpm -g
cnpm install vue
cnpm install --global vue-cli

3、创建项目

vue init webpack my-project

4、安装并配置elementUI和Axios

(1)安装

npm i element-ui -S
npm install axios -S

安装完成后,在package.json会出现依赖

 "dependencies": {
    "axios": "^0.18.0",
    "element-ui": "^2.6.3",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1"
  }

(2)配置:在src下的main.js中增加如下内容

import ElementUI from 'element-ui'
import '../node_modules/element-ui/lib/theme-chalk/index.css'
import axios from '../node_modules/axios'
import qs from '../node_modules/qs'
​
new Vue({
  ....
  axios,
  qs,
  ...
})

cdn引入方式

<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
​
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

vue去掉访问路径中的'#'(hash模式),在router目录下的index.js开启history模式,history模式使用 history.pushState API 来完成 URL 跳转而无须重新加载页面

export default new Router({
  mode: 'history',
  routes: [...]
})

 

(3)测试

(1)elementUI测试,修改项目中components下的HelloWorld.vue,更多详情参见官网

<!--修改模板如下-->
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
        <el-button type="primary" @click="visible = true">Button</el-button>
            <el-dialog :visible.sync="visible" title="Hello world">
            <p>Try Element</p>
        </el-dialog>
        <br><br>
        <el-button type="primary" @click="getRequest">Get测试</el-button>
        <el-button type="primary" @click="postRequest">Post测试</el-button>
    <h2>Ecosystem</h2>
  </div>
</template>
​
<!--在data内增加-->
visible: false

启动测试

cd my-project
npm run dev

(2)Axios请求测试

发送get请求

this.$axios.get('/hello')
            .then(function(response) {
            console.log(response);
            })
            .catch(function(err) {
            console.log(err);
            });

发送post请求

this.$axios.post('/sayHello',data,{headers:{'Content-Type':'application/x-www-form-urlencoded'}})
            .then(function(response) {
            console.log(response);
            })
            .catch(function(err) {
            console.log(err);
            });

测试结果如下:

Vue与Springboot的简单整合

Axios基本语法

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

Axios文档

5、创建springboot项目

SpringBoot JPA数据访问的详细内容参见官网指导手册

项目结构如图:

Vue与Springboot的简单整合

其中static目录下的文件从my-project打包而来,命令如下

npm run build

 用户注册后,会返回注册状态信息,再测试登录即可

Vue与Springboot的简单整合