first commit
This commit is contained in:
88
stores/user.js
Normal file
88
stores/user.js
Normal file
@@ -0,0 +1,88 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { wxLogin, wxGetUserProfile } from "@/utils/login.js";
|
||||
import { getPlatformProvider } from "@/utils/system";
|
||||
import { getUserInfo, getUserAsset } from "@/api/auth.js";
|
||||
|
||||
export const useUserStore = defineStore("user", {
|
||||
state: () => ({
|
||||
token: "",
|
||||
userInfo: {},
|
||||
}),
|
||||
actions: {
|
||||
setToken(token) {
|
||||
this.token = token;
|
||||
uni.setStorageSync("token", token); // 持久化 tokenx
|
||||
},
|
||||
setUserInfo(userInfo) {
|
||||
this.userInfo = userInfo;
|
||||
uni.setStorageSync("userInfo", JSON.stringify(userInfo)); // 持久化用户信息
|
||||
},
|
||||
loadFromStorage() {
|
||||
const token = uni.getStorageSync("token");
|
||||
const userInfoStr = uni.getStorageSync("userInfo");
|
||||
if (token) this.token = token;
|
||||
if (userInfoStr) {
|
||||
try {
|
||||
this.userInfo = JSON.parse(userInfoStr);
|
||||
} catch (e) {
|
||||
this.userInfo = {};
|
||||
}
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
this.token = "";
|
||||
this.userInfo = {};
|
||||
uni.removeStorageSync("token");
|
||||
uni.removeStorageSync("userInfo");
|
||||
},
|
||||
loadUserInfo() {
|
||||
const userStr = uni.getStorageSync("userInfo");
|
||||
if (userStr) {
|
||||
try {
|
||||
this.userInfo = JSON.parse(userStr);
|
||||
} catch (e) {
|
||||
this.userInfo = {};
|
||||
}
|
||||
}
|
||||
},
|
||||
async fetchUserInfo() {
|
||||
try {
|
||||
const res = await getUserInfo();
|
||||
if (res) {
|
||||
this.setUserInfo(res);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("fetchUserInfo error", e);
|
||||
}
|
||||
},
|
||||
async fetchUserAssets() {
|
||||
try {
|
||||
if (!this?.userInfo?.id) return;
|
||||
const res = await getUserAsset();
|
||||
if (res) {
|
||||
const newInfo = { ...this.userInfo, ...res };
|
||||
if (res.points !== undefined) {
|
||||
newInfo.points = res.points;
|
||||
}
|
||||
|
||||
if (res.exp !== undefined) {
|
||||
newInfo.exp = res.exp;
|
||||
}
|
||||
|
||||
if (res.level !== undefined) {
|
||||
newInfo.level = res.level;
|
||||
}
|
||||
this.setUserInfo(newInfo);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("fetchUserAssets error", e);
|
||||
}
|
||||
},
|
||||
logout() {
|
||||
this.userInfo = {};
|
||||
this.token = "";
|
||||
uni.removeStorageSync("userInfo");
|
||||
uni.removeStorageSync("token");
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user