結合上篇https://blog.csdn.net/xibei19921101/article/details/104717453
上篇是後端接口的代建,此處是前端項目的搭建
具體項目已上傳git
https://github.com/qigangye/spring_vue_demo
1.使用異步請求需要axios,那麼使用npm安裝axios
npm install axios -g
2.確認安裝好iview並在項目中引入iview以及iview樣式
3.在項目中引入axios
import axios from 'axios'
Vue.prototype.$axios = axios
4.繪製一個登錄界面(此處可以去iview官網http://v1.iviewui.com/components/form去下載一個模板)
在src/components目錄下新建一個vue文件
將iview的模板代碼稍作修改(設置屬性名的時候與後端請求接收的json屬性名一致)
注意:一個vue文件中的template標籤下只有一個主div
<template>
<div>
<template>
<div>
<Form ref="user" :model="user" :rules="ruleInline" inline>
<div>
<FormItem prop="username">
<Input type="text" v-model="user.userName" placeholder="請輸入用戶名">
<Icon type="ios-person-outline" slot="prepend"></Icon>
</Input>
</FormItem>
</div>
<div>
<FormItem prop="password">
<Input type="password" v-model="user.passWd" placeholder="請輸入密碼">
<Icon type="ios-lock-outline" slot="prepend"></Icon>
</Input>
</FormItem>
</div>
<div>
<FormItem>
<Button type="primary" @click="login()">登錄</Button>
</FormItem>
</div>
</Form>
</div>
</template>
</div>
</template>
<script>
export default {
name: 'Login',
data(){
return {
user: {
userName: '',
passWd: ''
},
ruleInline: {
userName: [
{ required: true, message: '用戶名不能爲空', trigger: 'blur' }
],
passWd: [
{ required: true, message: '密碼不能爲空', trigger: 'blur' },
{ type: 'string', min: 6, message: '密碼長度不能小於6', trigger: 'blur' }
]
},
}
},
methods:{
login(){
var user = this.user;
if(user.userName === '' || user.passWd === ''){
return false;
}
this.$axios.post('/api/userController/userLogin',user).then((response) => {
var status = response.data.code;
if(status === 200) {
console.log(response)
//路由跳轉
this.$router.push('/Helloworld');
} else {
alert(response.data);
}
}).catch((error) => {
console.log(response);
});
}
}
}
</script>
5.將繪製好的頁面註冊到路由中,就是router目錄下的index.js文件
6.在Login.vue文件下編寫js腳本
7.最後關鍵的一步,解決路由跨域的問題,可以在前端解決,也可以在springboot中使用跨域解決,此處使用前端配置解決,在config目錄下的index.js文件中加入幾行代碼
'/api': {
target: 'http://localhost:8089',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
若想使用springboot後端更改來解決跨域,參考https://www.bilibili.com/video/av85793766?p=1
8.工作完成,啓動項目,老規矩(後端要啓動)
npm install & npm run dev
然後瀏覽器地址欄輸入localhost:8080,輸入賬號密碼
點擊登錄
達到預期結果(response的日誌打印,跳轉HelloWorld頁面)
查看後端的日誌:
奈斯,一個簡單的前後端分離的項目就此搭建結束!!!