vue3中用户账号密码登录功能的实现|axios接收后端返回的数据处理|vue3+axios+python
一、后端数据
因为用户注册的时候,已经把注册信息递交到后端数据库里了,所以在用户登录的时候,后端直接读取数据库里的注册信息,看看登陆的用户名和密码匹不匹配即可。
这里我就简写,直接判断用户名=张三,密码等于123456了。
后端接收到登录数据后,需要给前端返回成功与否的信息,这里就直接返回一个对象数组。
# 接收用户名和密码,返回登录信息
def v3baiuserlogin(request, response=None):
_name = request.GET.get("userName")
_pwd = request.GET.get("pwd")
if _name != "张三":
response = HttpResponse('[{"id":"1","content":"用户名错误","judge":"Error"}]')
elif _pwd !="123456":
response = HttpResponse('[{"id":"2","content":"密码错误","judge":"Error"}]')
else:
response = HttpResponse('[{"id":"3","name":"张三","pwd":"123456","content":"登录成功","judge":"Success"}]')
response["Access-Control-Allow-Origin"] = "*"
return response
二、vue中用户账号密码登录功能
此需求未做表单验证。
**需求:**用户在登录页面输入账号密码,点击登录,后端验证登录成功与否。并弹出提示信息。
所用插件:
1.axios axios安装与使用链接
2.vue3的elementPlus。 vue3中elementPlus安装与使用
不影响此功能,仅用了它里面的alert框。
逻辑:用户用户名密码提交到后端,后端返回了数据,提示前端该怎么判断。
也可以把提示信息也写到后端,前端直接读取。在调用elementplus的提示函数时传参即可。
<template>
<div>
<div class="header">
<ul >
<li class="zhanghao">账号密码登录</li>
</ul>
<div class="text">
<input type="text" v-model="userName" autocomplete="off" placeholder="账号" />
</div>
<div class="password">
<input type="password" v-model="pwd" autocomplete="off" placeholder="密码" />
</div>
<button @click='Admin()'>登录</button>
</div>
</div>
</template>
<script>
import {
ElNotification } from 'element-plus'
export default{
name:"userlogin",
data(){
return{
userName:'',
pwd:'',
returnarr:'', //后端传过来的存储登录user的数组
cartArr:''
}
},
created(){
},
methods:{
//1.点击事件函数,点击登录 数据传到服务器端看是否注册过。服务器直接写的 张三 123456
Admin(){
this.sendData()
},
//2.接受服务器端传来的参数(判断yes or no)
sendData(){
var that=this;
this.$axios({
method:'get',
url:'http://127.0.0.1:8000/v3baiuserlogin/',
params:{
userName:this.userName, //2.1需要给后端传的俩参数
pwd:this.pwd
}
}).then(function(data){
that.returnarr=data.data //3.returnarr接收后端返回的参数
that.judgedata() //4.接受完参数就可以在这判断成功与否
});
},
//4.判断传过来的user信息,验证登录成功与否。
judgedata(){
if(this.returnarr[0].id==1){
// alert('您输入的用户名错误')
//应用elementplus组件,不应用就写alert也行
this.usernameerrortip()
}else if(this.returnarr[0].id==2){
// alert('您输入的密码有误')
this.pwderrortip()
}
//登录成功
if(this.returnarr[0].id==3){
console.log('登录成功')
this.loginsuccess()
//5.登陆成功之后要做的事情
//例如 缓存存入用户信息
localStorage.setItem("user",this.userName)
}
},
//elementplus里的3个alert弹出框
usernameerrortip(){
ElNotification({
title: '错误',
message: '您输入的用户名错误',
type: 'error',
})
},
pwderrortip(){
ElNotification({
title: '错误',
message: '您输入的密码错误',
type: 'error',
})
},
loginsuccess(){
ElNotification({
title: '成功',
message: '登录成功!',
type: 'success',
})
},
}
}
</script>