uni-app实现用户保持登录

因为这回的项目是app,所以不可避免的问题就是如何保持用户登录,第一次接触,在这个过程中踩了一些坑,其实只要熟悉了缓存原理就很好做,网上的解决方法也有很多,写一篇整理的帖子记录一下:

1.思路

这是当时不清楚整个流程的时候请教了一个朋友给的思路。
在这里插入图片描述

2.代码实现

login.vue
登录页的按钮及调用的方法:

<u-button type="primary" @click="submit" style="margin: 20rpx 0;">快速登录</u-button>
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let params = {
							auth_type: 'sms',
							mobile: this.form.mobile,
							sms_token: this.codeToken,
							tenant_id: '000000',
							grant_type: 'password',
							password: this.form.verification,
							secret_code: ''
						}
						this.$http.post('/api',params).then(res=>{
							this.timer = null
							//这里用了uni-app自带的方法uni.setStorageSync设置缓存存储的数据
							uni.setStorageSync('access_token', res.access_token)
							uni.setStorageSync('refresh_token', res.refresh_token)
							uni.setStorageSync('expires_in', new Date().valueOf()/3600 + res.expires_in)
							this.$store.dispatch('quickLogin/setUserInfo',res)  //使用dispatch将获取的数据存入vuex中
							this.setPaientInfo(res.user_id)
							this.setCommonHospital(res.user_id)
							uni.showToast({
								title: '跳转中...请稍后',
								duration: 2000,
								icon: 'success'
							})
							this.timer2 = setInterval(()=>{
								clearInterval(this.timer2)
								this.timer2 = null
								uni.switchTab({
									url: '/pages/center/index'
								})
							},2000)
						})
					} else {
						uni.showToast({
							title: '请正确填写信息',  //对话框错误捕捉信息展示
							duration: 3000,
							icon: 'none'
						})
					}
				});
			},

quickLogin.js文件

import http from "@/api/http.js"
const quickLogin = {
	namespaced: true,
	state: {
		userInfo: {},
	},
	mutations: {
		COMMIT_USERINFO(state,newInfo){
			state.userInfo = newInfo
		},
	},
	actions: {
		setUserInfo({commit},data){
			commit('COMMIT_USERINFO',data)
			commit('COMMIT_TOKEN',data.access_token)
		},
	}
}

export default quickLogin

检查一下session storage,保存成功。
在这里插入图片描述
退出登录使用uni.clearStorageSync()清空缓存,清空vuex里的数据就可以了。方法如下:

confirmLogout(){
				uni.clearStorageSync()
				this.$store.dispatch('quickLogin/setToken','')
				this.$store.dispatch('quickLogin/setUserInfo',{})
				uni.showToast({
					title: "已退出",
					icon: "none",
					duration: 3000
				})
				uni.navigateTo({
					url: '../../../pages/login/login'
				})
			}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值