vue3+flask 简易登录功能实现

功能说明

如果未登录,则跳转到登录组件;在登录组件中登录成功,则跳转到首页组件。用户信息在mysql数据库中。较为关键的几个点有:flask中session功能的应用和接收前端传递数据的方式、vue3中的组件跳转等。

一、前端Vue程序

1、创建登录组件Login.vue

<template>
  <el-row style="margin: 0.5rem 0;">
    <el-col :span="24">
        <h2 style="text-align: center;font-weight: bold;">用户登录</h2>
    </el-col>
  </el-row>
  <el-row style="margin: 0.5rem 0;">
    <el-col :span="24">
      <el-input v-model="un">
        <template #prepend>账号</template>
      </el-input>
    </el-col>
  </el-row>
  <el-row  style="margin: 0.5rem 0;">
    <el-col :span="24">
      <el-input v-model="pwd" type="password" show-password>
        <template #prepend>密码</template>
      </el-input>
    </el-col>
  </el-row>
  <el-row  style="margin: 0.5rem 0;text-align: center;">
    <el-col :span="24">
        <el-button type="primary" round @click="submithandle">提交</el-button>
        <el-button type="info" round>重置</el-button>
    </el-col>
  </el-row>
</template>

<script setup>
	import { ref } from "vue";
	import { useRouter } from "vue-router";  //引入vue路由对象
	import { ElMessage } from 'element-plus'
	import axios from "axios";
	
	const un = ref("");
	const pwd = ref("");
	const curRouter=useRouter() //创建vue路由实例
	function submithandle(){
	    if(un.value=="" || pwd.value=="")
	    {
	        ElMessage({
	            message: '请填完整再提交。',
	            type: 'error',
	        })
	    }
	    else
	    {
	        axios.post("/login",{"un":un.value,"pwd":pwd.value}).then(rs=>{
	            if(rs.data.code==1)
	            {
	                ElMessage({
	                    message: '登录成功!',
	                    type: 'success',
	                })
	                curRouter.push('/index') //跳转路由
	            }
	            else
	            {
	                ElMessage({
	                    message: '用户名或密码不正确,请重试',
	                    type: 'error',
	                })
	            }
	        })
	    }
	}
</script>

2、创建首页组件Index.vue

<template>
    welcome,{{ uname }}
</template>

<script setup>
	import {ref,onMounted} from 'vue'
	import { useRouter } from 'vue-router';
	import axios from 'axios'
	const curRouter=useRouter()
	const uname=ref('')
	onMounted(()=>{
	    axios.post("/islog").then(rs=>{
	        if(rs.data.code==0)
	        {
	            curRouter.push('/login')
	        }
	        else
	        {
	            uname.value=rs.data.uname
	        }
	    })
	})
</script>

3、路由配置文件index.js

import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login.vue'
import Index from '../components/Index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/index',
      name: 'index',
      component: Index
    }
  ]
})
export default router

二、后端flask程序

from flask import Flask 
from flask import request  #request用于接收前端发来的数据
import pymysql
import json  #json用于数据类型转换
from flask_cors import CORS  #设置跨域访问
from flask import session  #引入session保存登录状态

app = Flask(__name__) 
CORS(app, supports_credentials=True) #允许跨域
app.secret_key="anyChar"

db = pymysql.connect(host="localhost", port=3306, user='user', password='password', charset='utf8', database='yourDBname', cursorclass=pymysql.cursors.DictCursor) #连接数据库
mycursor = db.cursor() #创建游标对象

#首页组件中判断是否为登录状态
@app.route("/islog",methods=["POST"]) 
def islog(): 
    if session['uname'] is None:  #如果session不存在,则返回状态
        return({"code":0})
    else:
        return({"code":1,'uname':session.get('uname')})   #如果session存在,则返回session数据

#前端登录功能组件对应的后端程序
@app.route("/login",methods=["POST"]) 
def login(): 
    #以下3行代码为接受前端以post方式传递过来的数据
    jsondata=json.loads(request.data)   #字符串转json
    un=jsondata['un']
    pwd=jsondata['pwd']
    
    #查询数据库
    sql = "select * from users where uname='"+un+"' and pwd=md5('"+pwd+"')" 
    mycursor.execute(sql)  
    rs = mycursor.fetchone() 

	#处理查询结果
    if rs is not None:  #如果查询结果不为空,则创建session
        session['uid']=rs['uid']
        session['uname']=rs['uname']
        return ({'code':1,'uname':rs['uname']})
    else:
        return({'code':0})

if __name__ == '__main__':
    app.run(debug=True)  #调试状态运行,好处是代码修改保存后服务自动重启

你可能感兴趣的:(Vue,Python,flask,vue)