vue3+flask 简易登录功能实现

news/2024/7/10 1:59:40 标签: flask, vue

功能说明

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

一、前端Vue程序

vue_3">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>

vue_74">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_125">二、后端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)  #调试状态运行,好处是代码修改保存后服务自动重启

http://www.niftyadmin.cn/n/472813.html

相关文章

Windows安装使用Nacos并进行服务治理

Nacos简介 Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集&#xff0c;帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。 Nacos其实就是一个注册中心,用来管理和注册微服务 搭建Nacos环境 安装nacos(版本1.1.4) 下载网址 htt…

设计模式第14讲——享元模式(Flyweight)

目录 一、什么是享元模式 二、角色组成 三、优缺点 四、应用场景 4.1 生活场景 4.2 java场景 五、代码实现 5.0 代码结构 5.1 Bike——抽象享元类&#xff08;FlyWeight&#xff09; 5.2 具体享元类&#xff08;ConcreteFlyWeight&#xff09; 5.3 BikeFactory——享元…

什么是Natural Language Understanding(NLU)?

文章目录 1.什么是NLU&#xff1f;2.NLU的应用有哪些&#xff1f;3.NLU的实现方式有哪些&#xff1f;4.NLU实现的难点 1.什么是NLU&#xff1f; 自然语言理解(Natural Language Understanding, NLU)是所有支持机器理解文本内容的方法模型或任务的总称&#xff0c;即能够进行常…

SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现

系列文章&#xff1a; SpringBoot Vue前后端分离项目实战 || 一&#xff1a;Vue前端设计 SpringBoot Vue前后端分离项目实战 || 二&#xff1a;Spring Boot后端与数据库连接 SpringBoot Vue前后端分离项目实战 || 三&#xff1a;Spring Boot后端与Vue前端连接 文章目录 前端…

在 CentOS 上安装 Docker Engine

文章目录 在 CentOS 上安装 Docker Engine先决条件操作系统要求卸载旧版本 安装方法使用 rpm 存储库安装设置存储库安装 Docker Engine安装最新版本安装指定版本 以非 root 用户身份管理 Docker配置 Docker 以使用 systemd 启动 参考官方文档&#xff1a; https://docs.docker…

Python安装教程(初学者很实用)

一、Python环境搭建 1、下载Python 进入Python官网下载安装包 https://www.python.org/ 2、选择合适的版本&#xff0c;点击下载 3、安装Python 双击安装软件 等待安装完成 出现【setup was successful】&#xff0c;表示安装成功 4、检验是否安装成功 通过【winr】调出…

uniapp在IOS系统上无法横屏问题

问题:在安卓或者系统系统上调用横屏plus.screen.lockOrientation(‘landscape-primary’);失效。 解决方案:在manifest.json配置 代码如下: “flexible” : true, “screenOrientation” : [ “portrait-primary”, “landscape-primary” ], /* 5App特有相关 */"app-plu…

实施预测性维护的策略和实践探讨

随着工业设备复杂性和关键性的增加&#xff0c;传统的计划性维护方法已经无法满足现代工业的需求。预测性维护作为一种基于设备状态和数据分析的维护策略&#xff0c;能够准确预测设备故障&#xff0c;降低停机时间&#xff0c;提高生产效率和设备可靠性。在实施预测性维护之前…