123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import { defineStore } from 'pinia';
- import { smsLogin, passwordLogin, logout } from '@/api/common'
- // 默认账户信息
- const defaultAccountInfo = {
- accessToken: '',
- expiresTime: '',
- openid: '',
- refreshToken: '',
- userId: ''
- }
- export const userStore = defineStore('user', {
- state: () => {
- const userLocal = uni.getStorageSync('user')
- const userInfo = userLocal ? JSON.parse(userLocal) : {}
- return {
- phone: null,
- userInfo: userInfo.userInfo ?? {},
- isLogin: !!uni.getStorageSync('token'), // 登录状态
- refreshToken: uni.getStorageSync('refresh-token'), // 用户切换
- lastUpdateTime: 0, // 上次更新时间
- accountInfo: { ...defaultAccountInfo }, // 账号信息
- }
- },
- actions: {
- setLogin (val) {
- this.isLogin = val
- },
- // 登录
- async handleSmsLogin (query, index = 0, isGetData = true) {
- this.phone = query.phone
- const apiList = [smsLogin, passwordLogin]
- const { data, code } = await apiList[index](query)
- if (code === 0) {
- uni.showToast({
- title: '登录成功'
- })
- }
- this.accountInfo = data
- },
- // 设置 token
- setToken(token = '', refreshToken = '') {
- if (token === '') {
- this.isLogin = false;
- this.refreshToken = ''
- uni.removeStorageSync('token');
- uni.removeStorageSync('refresh-token');
- } else {
- this.isLogin = true;
- uni.setStorageSync('token', token);
- this.refreshToken = refreshToken
- uni.setStorageSync('refresh-token', refreshToken);
- this.loginAfter();
- }
- return this.isLogin;
- },
- // 更新用户相关信息 (手动限流,5 秒之内不刷新)
- async updateUserData() {
- if (!this.isLogin) {
- this.resetUserData();
- return;
- }
- // 防抖,5 秒之内不刷新
- const nowTime = new Date().getTime();
- if (this.lastUpdateTime + 5000 > nowTime) {
- return;
- }
- this.lastUpdateTime = nowTime;
- },
- // 重置用户默认数据
- resetUserData() {
- // 清空 token
- this.setToken();
- // 清空用户相关的缓存
- this.userInfo = {}
- this.phone = ''
- this.accountInfo = { ...defaultAccountInfo };
- },
- // 登录后,加载各种信息
- async loginAfter() {
- await this.updateUserData();
- },
- // 登出系统
- async handleLogout() {
- try {
- await logout(uni.getStorageSync('token'))
- this.resetUserData()
- } catch (error) {
- console.log('handleLogout:error', error)
- // if (error?.msg === '企业登录授权错误,请重新登录')
- this.resetUserData()
- }
- // return !this.isLogin;
- }
- },
- persist: {
- storage: {
- setItem(key, value) {
- uni.setStorageSync(key, value)
- },
- getItem(key) {
- return uni.getStorageSync(key)
- },
- },
- }
- })
|