Vue+SpringBoot 前後端分離 簡單登入
阿新 • • 發佈:2020-12-31
前置工作
我們這裡前後端分離以登入為例子,前置工作搭建好環境。
在寫完表單後,我們要寫到表單提交真正訪問到後臺的時候就不能使用Ajax了,這裡要使用Axios代替Ajax。Axios封裝了Ajax,使用起來也是很方便的。
注意因為是前後端分離的專案,所以要把前後端的埠設定的不同,避免衝突!!!
前端部分程式碼
<!-- 表單 --> <el-form ref="loginFormRef" :model="loginForm" class="login_form" label-width="90" :rules="loginRules"> <el-form-item prop="username"> <el-input v-model="loginForm.username" prefix-icon="iconfont icondenglu"></el-input> </el-form-item> <el-form-item prop="password"> <el-input type="password" v-model="loginForm.password" prefix-icon="iconfont iconmima"></el-input> </el-form-item> <el-form-item class="btns"> <el-button type="primary" @click="login()">提交</el-button> <el-button type="info" @click="resetLoginForm()">重置</el-button> </el-form-item> </el-form>
後端程式碼
@RestController
public class LoginController {
@RequestMapping("/login")
public String login(@RequestBody User user) {
System.out.println("user:" + user);
return "ok";
}
}
引入Axios
安裝命令 npm install --save axios vue-axios
main.js中引入Axios
// 匯入
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
// 掛載axios
Vue.prototype.$http = axios
// 設定訪問根路徑
axios.defaults.baseURL = "http://localhost:9000"
login方法
methods:{ resetLoginForm(){ this.$refs.loginFormRef.resetFields(); }, login(){ this.$refs.loginFormRef.validate(async valid => { if( !valid ) return; const{data:res} = await this.$http.post("login",this.loginForm) if( res == "ok" ){ this.$message.success("操作成功") this.$router.push({path:"/home"}); }else{ this.$message.error("操作失敗") } }) } }
後臺成功接收到資料。