Spring Boot + Vue 前后端分离式开发实践
采用Vue CLI v4.5.15
构建Vue2
项目
创建项目
vue create lightcloud
cd lightcloud
npm run serve
PS D:\Project> vue create lightcloud
? Your connection to the default npm registry seems to be slow.
Use https://registry.npm.taobao.org for faster installation? Yes
Vue CLI v4.5.15
? Please pick a preset: Default ([Vue 2] babel, eslint)
Vue CLI v4.5.15
✨ Creating project in D:\Project\lightcloud.
🗃 Initializing git repository...
⚙️ Installing CLI plugins. This might take a while...
> yorkie@2.0.0 install D:\Project\lightcloud\node_modules\yorkie
> node bin/install.js
setting up Git hooks
done
> core-js@3.19.1 postinstall D:\Project\lightcloud\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"
added 1263 packages from 655 contributors in 74.426s
84 packages are looking for funding
run `npm fund` for details
🚀 Invoking generators...
📦 Installing additional dependencies...
added 53 packages from 36 contributors in 8.864s
89 packages are looking for funding
run `npm fund` for details
⚓ Running completion hooks...
📄 Generating README.md...
🎉 Successfully created project lightcloud.
👉 Get started with the following commands:
$ cd lightcloud
WARN Skipped git commit due to missing username and email in git config, or failed to sign commit.
You will need to perform the initial commit yourself.
PS D:\Project\lightcloud> npm run serve
> lightcloud@0.1.0 serve D:\Project\lightcloud
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 2382ms 上午9:58:24
App running at:
- Local: http://localhost:8081/
- Network: http://192.168.0.5:8081/
Note that the development build is not optimized.
To create a production build, run npm run build.
配置跨域支持
config/index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
//代理请求路径
proxyTable: {
'/api':{
target:"http://localhost:8080/",
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
反向代理
src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//引入axios
import axios from 'axios'
import Axios from 'axios';
Vue.prototype.$ajax = axios
// 设置全局的axios
Vue.prototype.$axios = Axios
// 设置基本路径
Axios.defaults.baseURL = 'http://localhost:8080/api'
// 设置post请求的数据类型
// Axios.defaults.headers.post['Content-Type']='application/json'
// Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
// el: '#app',
router,
// components: { App },
render: h => h(App)
}).$mount("#app")
配置路由
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/login',
name: 'Login',
component: require('@/components/Login').default
}
,
{
path: '/index',
name: 'AppIndex',
component: require('@/components/home/Appindex').default
}
]
})
src/App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
添加页面
src\components\Login.vue
<template>
<div>
用户名:<input type="text" v-model="loginForm.username" placeholder="请输入用户名"/>
<br><br>
密码: <input type="password" v-model="loginForm.password" placeholder="请输入密码"/>
<br><br>
<button v-on:click="login">登录</button>
</div>
</template>
<script>
export default {
name: 'Login',
data () {
return {
loginForm: {
username: '',
password: ''
},
responseResult: []
}
},
methods: {
login () {
this.$axios
.post('/login', {
username: this.loginForm.username,
password: this.loginForm.password
})
.then(successResponse => {
if (successResponse.data.code === 200) {
this.$router.replace({path: '/index'})
}
})
.catch(failResponse => {
})
}
}
}
</script>
src\components\home\Appindex.vue
登陆成功