Files
uniapp-im-shop/stores/token.js

49 lines
1.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { STORAGE_KEYS } from '@/constants/storage-keys'
import { setTokenData, getToken, removeToken } from '@/utils/storage'
/** 登录状态 */
export const useTokenStore = defineStore(STORAGE_KEYS.TOKEN, () => {
// 从本地存储获取token
const token = ref(getToken() || null)
const isLogin = ref(!!token.value)
/** 设置token并保存到本地 */
const setToken = newToken => {
token.value = newToken
isLogin.value = true
setTokenData(newToken)
}
/** 清除token */
const clearToken = () => {
token.value = null
isLogin.value = false
removeToken()
}
/** 检查token是否有效可扩展过期时间判断 */
const checkToken = () => {
// 简单判断token存在且不为空
return !!token.value
}
/** 验证token是否过期实际项目中可添加过期时间判断 */
const isTokenExpired = () => {
// 示例如果token中包含过期时间这里可以判断
// 例如const expireTime = parseInt(token.value.split('.')[1]);
// return Date.now() > expireTime * 1000;
return false // 默认不过期
}
return {
token,
isLogin,
setToken,
clearToken,
checkToken,
isTokenExpired
}
})