cankao-h5/src/stores/user/index.ts

116 lines
2.9 KiB
TypeScript
Raw 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 { login } from "@/api";
import { Session } from "@/utils/storage";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
type IUserInfos = {
id?: string;
phone: string;
name?: string;
auth: string[];
role: string[];
accountType: number;
};
const storeSetup = () => {
const token = ref(Session.get("token"));
const userInfos = ref<IUserInfos>({
phone: "",
name: "",
auth: [], // 首页导航菜单权限存在, 暂不使用
role: [], // 角色,暂不使用
accountType: 0, // 账号类型0:测试 1:正式
});
const setUserInfos = (payload: Partial<IUserInfos>) => {
userInfos.value = { ...userInfos.value, ...payload };
Session.set("userInfos", userInfos.value);
};
const getUserInfos = () => {
if (Session.get("userInfos")) {
userInfos.value = Session.get("userInfos");
}
return userInfos.value;
};
// 设置 token
const setToken = (payload: string) => {
token.value = payload;
Session.set("token", payload);
};
// 获取 token
const getToken = () => {
return token.value;
};
// 登录状态
const isLogin = computed(() => {
return !!token.value;
});
// 试用 | 正式
const isUserType = computed(() => {
// 0:测试 1:正式 判断账号类型
return getUserInfos()?.accountType === 1 ? true : false;
// 为了兼容之前的版本,暂时不区分账号类型,先放开正式账号和测试账号的限制
// return true;
});
// 登录
const onLogin = async (data: any): Promise<any> => {
return new Promise(async (resolve, reject) => {
uni.showLoading({
title: "登录中",
mask: true,
});
try {
const params = {
phone: data.phone,
smsCode: data.code,
};
const result = await login(params);
uni.hideLoading();
if (result.code === 200) {
window.aplus_queue.push({
action: "aplus.record",
arguments: [
"login",
"CLK",
{
phone: data.phone,
},
],
});
setToken(result.data.token);
setUserInfos({ ...result.data });
// 为了兼容之前的版本,暂时保留 userPhone 字段
Session.set("userPhone", data.phone);
uni.showToast({
title: "登录成功",
icon: "success",
});
} else {
uni.showToast({
title: result.msg,
icon: "error",
});
}
resolve(result);
} catch (error) {
uni.hideLoading();
console.log(error, "<=== error");
reject(error);
}
});
};
return { isLogin, userInfos, getToken, onLogin, getUserInfos, isUserType };
};
export const useUserStore = defineStore("user", storeSetup);