后端的url登錄接口
先修改main.js文件
// 導(dǎo)入Ajax 前后端數(shù)據(jù)傳輸
import axios from "axios";
const app = createApp(App)
//vue3.0使用app.config.globalProperties.$http
app.config.globalProperties.$http = axios
app.mount('#app');
login.vue
頁面顯示部分
<template>
<el-form ref="loginForm" :model="loginForm" :rules="rules" >
<el-form-item label="用戶">
<el-input v-model="loginForm.username" placeholder="請(qǐng)輸入用戶名"> </el-input>
</el-form-item>
<el-form-item label="密碼">
<el-input v-model="loginForm.password" type="password" placeholder="請(qǐng)輸入密碼" show-password></el-input>
<el-form-item>
<el-button @click="login">登錄</el-button>
</el-form-item>
</div>
</div>
</template>
登錄過程的js 點(diǎn)擊登錄按鈕 methos里面調(diào)用login登錄方法
export default {
name: "Login",
data(){
return{
// 登錄表單的數(shù)據(jù)綁定對(duì)象
loginForm: {
username: 'admin',
password: '123'
}
},
methods:{
login(){
this.$refs.loginForm.validate(valid => {
if (!valid) return
//登錄調(diào)用的doLogin進(jìn)行登錄
const result = this.$http.post('/api/doLogin',this.loginForm)
//先打印到瀏覽器控制臺(tái),看結(jié)果
console.log(result)
// 跳轉(zhuǎn)到home頁面
this.$router.push('/home')
})
}
}
}
此時(shí)前端有跨域問題 先配置跨域
vue.config.js? 項(xiàng)目中如果沒有這個(gè)文件 請(qǐng)自行創(chuàng)建。
module.exports = {
// 基本路徑 baseURL已經(jīng)過時(shí)
publicPath: './',
// 輸出文件目錄
outputDir: 'dist',
// eslint-loader 是否在保存時(shí)檢查
lintOnSave: false,
devServer: {
// 前端顯示端口號(hào)
port: 8080,
// 配置不同的后臺(tái)API地址
proxy: {
'/api': {
target: 'http://localhost:8000/api', // 后臺(tái)地址,根據(jù)實(shí)際后端接口
ws: true,
changeOrigin: true, //允許跨域
secure: false, //是否為https接口
pathRewrite: {
'^/api': ''
}
}
}
}
}
此時(shí)可以看到跳轉(zhuǎn)到登錄到home頁面
?完整的后端登錄方法?文章來源:http://www.zghlxwxcb.cn/news/detail-802105.html
消息提示使用elementPlus 的Elmessage?文章來源地址http://www.zghlxwxcb.cn/news/detail-802105.html
methods:{
login(){
const that = this
this.$refs.loginForm.validate(async valid => {
if (!valid) return
// 將loginForm對(duì)象轉(zhuǎn)換為查詢字符串
var data = qs.stringify(this.loginForm)
// 由于data屬性是一個(gè)json對(duì)象,需要進(jìn)行解構(gòu)賦值{data:result},進(jìn)行狀態(tài)碼判斷
await this.$http.post('/api/doLogin',data).then(function (response){
if (response.data.status === 200){
console.log('登錄成功')
that.$message.success("登錄成功")
that.$router.push('/home')
}else {
console.log('登錄失敗,api后端接口狀態(tài)',response.data.status)
that.$message.error("登錄失敗接口狀態(tài)", response.data.status)
}
})
})
}
}
到了這里,關(guān)于vue3+elementPlus登錄向后端服務(wù)器發(fā)起數(shù)據(jù)請(qǐng)求Ajax的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!