10天内人工登陆过的账号,打开APP时自动登录。 10天之后需要在登录页面,人工再点登陆,此时无需重新输入账号密码。

思路:
在第一次登录成功的回调里,获取登录的账号密码以及登录的时间,将账号和密码以及时间进行本地存储,方便下次登录进行判断。
接下来就是判断10天内是否登录过,也就是第二次登录的时候,要先判断有没有本地存储的账号和密码以及第一次登录时间,如果有,获取现在的时间,然后拿到当前时间和上次登录时间的时间差,然后进行天数换算,最后判断这个天数是否大于10就ok了。

代码如下:
首先在登录成功的回调里将需要的信息进行存储

login() {
				console.log("login")
				const that = this
				that.$u.api
					.loginApi({
						username: that.model.username,
						password: that.model.password,
					})
					.then((res) => {
						if (res.success) {				
					    	//获取账号密码进行存储	
							uni.setStorageSync('username', that.model.username)
							uni.setStorageSync('password', that.model.password)
							//获取登录时间进行存储
							 var now = new Date(); //获取登录时间
							 uni.setStorageSync('LoginDate',now)			
							 
							uni.reLaunch({
								url: '../index/index',
							})
						} else {
							that.$refs.uToast.show({
								title: res.message,
								position: 'top',
								type: 'error',
								icon: true,
							})
						}
					})
			},

然后,在onLoad生命周期中进行判断,获取第一次登录的账号密码和时间。

if (uni.getStorageSync('username') && uni.getStorageSync('password')&&uni.getStorageSync('LoginDate')) {
				var nowDate = new Date(); //获取现在时间
				let loginDate = uni.getStorageSync('LoginDate') //获取上次登录时间

				// 然后拿到当前时间和上次登录时间的时间差,毫秒数
				var deltaTime = (nowDate - loginDate) / 1000; //上次时间和当前时间相差的毫秒数/1000换算出总的秒数
				var d = Math.floor(deltaTime / 3600 / 24) //换算天数
				// console.log(d,'登录相差时间') 
				if (d <= 10) {
					this.login()
					console.log('自动登录')
				}
			}

欧克,到此结束,有问题或者更好的方法欢迎评论区留言~~

猜你喜欢

转载自blog.csdn.net/Quentin0823/article/details/131450469