基于uniapp的登录状态保持(APP免登录)

2024-08-31 09:28
文章标签 uniapp app 登录 状态 保持

本文主要是介绍基于uniapp的登录状态保持(APP免登录),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于uniapp的登录状态保持(APP免登录)

           本文介绍了uniapp的登录状态保持(APP免登录)实现方法。在rouyi-uniapp框架开发中,解决用户退出软件/关闭应用/更新安装包后,再打开进入应用需要重新登录,不符合用户使用习惯。本文介绍了如何通过将用户登录信息存储到缓存和文件中,判断用户登录状态直接进入应用。用户登录信息用必要存储到文件中,解决安装更新包更新后用户私有应用缓存被删除。

一、主要思路

  1. 改造登录方法,登录成功后,留存登录状态和登录信息、token等到缓存和本地txt文件中。(安装更新包更新后用户私有应用缓存被删除, 存储到文件中可解决问题)
  2. App.vue为公共组件,每次打开应用或者任意页面都会执行方法。在该文件中写入读取缓存和本地txt文件的方法,如果留存用户登录信息,则自动执行登录方法并跳转到首页。如果缓存和文件里都没有用户登录信息,则跳转到登录页。

二、Uniapp主要技术应用

1、uniapp本地缓存(非持久化)

const userInfo = uni.getStorageSync('userInfo'); //同步获取本地数据uni.setStorage({   key: 'userInfo',   data: user,});//设置本地存储数据

2、Uniapp文件缓存(持久化)

//文件缓存插件filePersistentIO读取文件this.$filePersistentIO.read('JTG_USR_TOKEN_INFO.txt').then(res => {loginInfoFromFile = resreturn loginInfoFromFile/*          console.log('loginInfoFromFile   res  ======================>')console.log(JSON.stringify(res))console.log(loginInfoFromFile)*/})//文件缓存插件filePersistentIO写入文件this.$filePersistentIO.storage('JTG_USR_INFO.txt', loginInfo)

3、文件缓存插件

plugins/filePersistentIO.js

// 数据持久化存储
// let addr = "file://storage/emulated/0/京唐港app/";
// let addr = "file:///storage/emulated/0/";
let addr = "JTGUser/Info/";  // 手机存储的文件位置export default {storage(className, data) {plus.io.requestFileSystem(// plus.io.PRIVATE_DOC, // 程序私有文档目录常量// plus.io.PUBLIC_DOWNLOADS, // 程序私有文档目录常量plus.io.PUBLIC_DOCUMENTS,fs => {// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象fs.root.getFile(addr + className,{create: true},// 文件不存在则创建fileEntry => {// 文件在手机中的路径fileEntry.createWriter(writer => {// 写入文件成功完成的回调函数writer.onwrite = e => {//console.log('写入成功');};// 向文件中写入数据writer.write(JSON.stringify(data));// 写入完成回调writer.onwriteend = function(res) {console.log('写入文件成功', res.target.fileName);};// 写入错误回调writer.onerror = function(err) {console.error('写入文件失败', err);};});},e => {console.log('getFile failed: ', e);});},e => {console.log(e.message);});},read(className) {let that = this;return new Promise((resolve, reject) => {plus.io.requestFileSystem(// plus.io.PRIVATE_DOC,// plus.io.PUBLIC_DOWNLOADS,plus.io.PUBLIC_DOCUMENTS,fs => {fs.root.getFile(addr + className,{create: false},fileEntry => {fileEntry.file(function(file) {console.log('文件大小:' + file.size + '-- 文件名:' + file.name);//创建读取文件对象let fileReader = new plus.io.FileReader();//以文本格式读取文件数据内容fileReader.readAsText(file, 'utf-8');//文件读取操作完成时的回调函数fileReader.onloadend = (evt) => {console.log(evt.target.result)console.log('evt.target.result')console.log(JSON.parse(evt.target.result),'JSON.parse(evt.target.result)')resolve(JSON.parse(evt.target.result))// sURL = JSON.parse(evt.target.result).URL;}// fileReader.onloadend = function(evt) {//     resolve(evt.target.result)// };});},e => {reject(e);});},e => {reject(e);console.log(e.message);});})}
}

3、插件引入

plugins/index.js

import filePersistentIO from './filePersistentIO'Vue.prototype.$filePersistentIO = filePersistentIO

三、实现案例

1、登录方法

登录信息持久化存储和缓存

(1)pages/login.vue

import {mapMutations}from 'vuex';...mapMutations(['login']),// 密码登录
async pwdLogin() {this.$store.dispatch('Login', this.loginForm).then(() => {this.$modal.closeLoading()//将登陆成功后的账号/密码放入到缓存let loginInfo = {username: this.loginForm.username,password: this.loginForm.password}uni.setStorage({key: 'loginInfo',data: loginInfo,});/** 登录信息持久化存储  */// 登录成功后将用户名密码存储到文件【安装包更新后-用户名密码自动填充,但不免登录】this.$filePersistentIO.storage('JTG_USR_INFO.txt',loginInfo)this.loginSuccess()}).catch(() => {if (this.captchaEnabled) {this.getCode()}})
},

 

  // 登录成功后,处理函数loginSuccess(result) {    // 设置用户信息this.$store.dispatch('GetInfo').then(res => {let userInfo = {userId: res.user.userName,token: uni.getStorageSync("token"),phone: res.user.phonenumber,userName: res.user.userName,jurisdiction: res.user.roleS,}   console.log("state"+uni.getStorageSync("state"))console.log("userinfo"+userInfo)debuggerthis.login(userInfo)  this.$tab.reLaunch('/pages/index')})
}
getLoginInfoFromFile(){/** 持久化存储数据读取 */let loginInfoFromFile = nullthis.$filePersistentIO.read('JTG_USR_INFO.txt').then(res => {loginInfoFromFile = resif (this.loginForm.username != '' && (loginInfoFromFile != "" && loginInfoFromFile.username == '' && loginInfoFromFile.password == '')) {this.loginForm.username = loginInfoFromFile.usernamethis.loginForm.password = loginInfoFromFile.password}/*          console.log('loginInfoFromFile   res  ======================>')console.log(JSON.stringify(res))console.log(loginInfoFromFile)*/})
},

  (2)store/index.js

Mutation触发此处的login,将登录信息存储到缓存。退出登录时清除登录信息。

import Vue from 'vue'
import Vuex from 'vuex'
import user from '@/store/modules/user'
import businessGlobeVariable from '@/store/modules/businessGlobeVariable'
import getters from './getters'Vue.use(Vuex)const store = new Vuex.Store({modules: {user,businessGlobeVariable},state: {hasLogin:false,        //用户是否登录userInfo:{}             //用户数据},mutations: {// 登录login(state,user){//登录状态为已登录state.hasLogin = truestate.userInfo = user//储存用户数据到本地uni.setStorage({key: 'userInfo',data: user,});console.log('登陆成功')console.log(state.hasLogin,state.userInfo)},// 退出登录logout(state,user){//登录状态为未登录state.hasLogin = falsestate.userInfo = {}//删除本地储存uni.removeSavedFile({key: 'userInfo',})console.log('退出登录')console.log(state.hasLogin,state.userInfo)}},actions: {},getters
})export default store

2、App.vue根组件读取登录缓存和文件

onLaunch: function() {
// 加入如下代码const userInfo = uni.getStorageSync('userInfo'); //同步获取本地数据//判断本地缓存是否存在数据if (userInfo != "") {//传到vuex里面储存起来,并改变登录状态this.login(userInfo)// 成功即跳转到首页this.$tab.reLaunch('/pages/index')}
},

checkLogin() {//debuggerconsole.log('getToken()=>'+getToken())if (!getToken()) {this.$tab.reLaunch('/pages/login')}else{const userInfo = uni.getStorageSync('userInfo'); //同步获取本地数据const userInfo1 = this.getLoginTokenInfoFromFile(); //同步获取本地数据(更新安装包后,缓存删除,从文件读取)//判断本地缓存是否存在数据if (userInfo != "") {//传到vuex里面储存起来,并改变登录状态this.login(userInfo)this.$tab.reLaunch('/pages/index')}else if (userInfo1 != "") {//传到vuex里面储存起来,并改变登录状态this.login(userInfo1)this.$tab.reLaunch('/pages/index')}}
},
getLoginTokenInfoFromFile(){/** 持久化存储数据读取 (用户名及token自动登录)*/let loginInfoFromFile = nullthis.$filePersistentIO.read('JTG_USR_TOKEN_INFO.txt').then(res => {loginInfoFromFile = resreturn loginInfoFromFile/*          console.log('loginInfoFromFile   res  ======================>')console.log(JSON.stringify(res))console.log(loginInfoFromFile)*/})
},

这篇关于基于uniapp的登录状态保持(APP免登录)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1123513

相关文章

Android App安装列表获取方法(实践方案)

《AndroidApp安装列表获取方法(实践方案)》文章介绍了Android11及以上版本获取应用列表的方案调整,包括权限配置、白名单配置和action配置三种方式,并提供了相应的Java和Kotl... 目录前言实现方案         方案概述一、 androidManifest 三种配置方式

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言

Flutter监听当前页面可见与隐藏状态的代码详解

《Flutter监听当前页面可见与隐藏状态的代码详解》文章介绍了如何在Flutter中使用路由观察者来监听应用进入前台或后台状态以及页面的显示和隐藏,并通过代码示例讲解的非常详细,需要的朋友可以参考下... flutter 可以监听 app 进入前台还是后台状态,也可以监听当http://www.cppcn

Oracle登录时忘记用户名或密码该如何解决

《Oracle登录时忘记用户名或密码该如何解决》:本文主要介绍如何在Oracle12c中忘记用户名和密码时找回或重置用户账户信息,文中通过代码介绍的非常详细,对同样遇到这个问题的同学具有一定的参... 目录一、忘记账户:二、忘记密码:三、详细情况情况 1:1.1. 登录到数据库1.2. 查看当前用户信息1.

MobaXterm远程登录工具功能与应用小结

《MobaXterm远程登录工具功能与应用小结》MobaXterm是一款功能强大的远程终端软件,主要支持SSH登录,拥有多种远程协议,实现跨平台访问,它包括多会话管理、本地命令行执行、图形化界面集成和... 目录1. 远程终端软件概述1.1 远程终端软件的定义与用途1.2 远程终端软件的关键特性2. 支持的

MySQL 中的服务器配置和状态详解(MySQL Server Configuration and Status)

《MySQL中的服务器配置和状态详解(MySQLServerConfigurationandStatus)》MySQL服务器配置和状态设置包括服务器选项、系统变量和状态变量三个方面,可以通过... 目录mysql 之服务器配置和状态1 MySQL 架构和性能优化1.1 服务器配置和状态1.1.1 服务器选项

linux进程D状态的解决思路分享

《linux进程D状态的解决思路分享》在Linux系统中,进程在内核模式下等待I/O完成时会进入不间断睡眠状态(D状态),这种状态下,进程无法通过普通方式被杀死,本文通过实验模拟了这种状态,并分析了如... 目录1. 问题描述2. 问题分析3. 实验模拟3.1 使用losetup创建一个卷作为pv的磁盘3.

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

通过prometheus监控Tomcat运行状态的操作流程

《通过prometheus监控Tomcat运行状态的操作流程》文章介绍了如何安装和配置Tomcat,并使用Prometheus和TomcatExporter来监控Tomcat的运行状态,文章详细讲解了... 目录Tomcat安装配置以及prometheus监控Tomcat一. 安装并配置tomcat1、安装

Linux之进程状态&&进程优先级详解

《Linux之进程状态&&进程优先级详解》文章介绍了操作系统中进程的状态,包括运行状态、阻塞状态和挂起状态,并详细解释了Linux下进程的具体状态及其管理,此外,文章还讨论了进程的优先级、查看和修改进... 目录一、操作系统的进程状态1.1运行状态1.2阻塞状态1.3挂起二、linux下具体的状态三、进程的