1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
<template>
<view>
<view v-if="isvistor">
<button @click="jumpLogin">游客状态,去登录</button>
</view>
<view v-else>
<text>已经登录</text>
<!-- 清除登录状态 -->
<button type="primary" @click="clearLogin">退出登录</button>
</view>
</view>
</template>
<script>
import { mapMutations } from 'vuex';
export default {
computed: {
hasLogin() {
return this.$store.state.user.hasLogin
},
visitorLogin() {
return this.$store.state.user.visitorLogin
},
},
data() {
return {
isvistor: false,
}
},
onLoad() {
if (this.hasLogin && !this.visitorLogin) {
console.log('用户正式登录,用正式token请求所有需要的信息')
this.isvistor = false;
} else {
this.isvistor = true;
// 获取游客的token
this.loginByVistor();
}
// token过期处理
// 假设约定的规则时 token过期时间小于24小时就刷新token
if (this.isWithin24Hours(uni.getStorageSync('expire')) == true) {
//使用setTimeOut模拟,在真实环境里这里应该是发送请求,从后端获取新的token
setTimeOut(()=>{
// console.log('刷新token成功')
let newToken = 'asdfgjgduyfhsdfjhgf'
let newRefreshToken = 'qwrtyweftufrgbnh'
uni.setStorageSync('myToken', newToken);
this.refreshLogin(newRefreshToken)
uni.setStorageSync('expire', res.data.expire);
}, 1000)
}
// token过期处理 END
},
methods: {
...mapMutations('user', ['login', 'visLogin', 'logout','refreshLogin']),
loginByVistor() { //获取到游客身份的token
let obj = {
username: 'temp',
password: '111111',
}
let token = uni.getStorageSync('myToken')
// 获取临时token
uni.request({
url: `${serverUrl}/temp`,
data: obj,
method: "POST",
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${token}`
},
success: (res) => {
//登录成功后改变vuex的状态,并退出登录页面
if (res.code === 200) {
this.visLogin(res.data.token);
console.log('游客身份,用临时token请求游客可以看到的信息')
}
}
})
},
jumpLogin() {
uni.reLaunch({
url: '/pages/login/login'
})
},
// 退出登录/清除缓存
clearLogin() {
if (this.hasLogin) {
this.logout()
uni.reLaunch({
url: '/pages/login/login'
})
}
},
isWithin24Hours(expireTime) {
const currentTime = new Date();
const difference = Math.abs(expireTime - currentTime);
const hoursDifference = Math.floor(difference / (1000 * 60 * 60));
return hoursDifference <= 24;
},
}
}
</script>
|