You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
zhishifufei_uniapp/store/modules/app.js

88 lines
2.4 KiB

9 months ago
import { SET_LOGIN, SET_LOGOUT, SET_ROOT_FONT, UPDATE_USER_INFO } from "@/store/types/muations-types";
import { VALID_LOGIN_STATUS } from "@/store/types/action-types";
import { validLoginStatus } from "@/api/user";
import utils from "@/utils/utils";
import baseConfig from "@/config";
import { USER_INFO_KEY, COOKIE_KEY, TOKEN_KEY } from "@/constants/storage-keys";
const mergeUserInfo = (userInfo) => {
const { avatar, ...args } = userInfo;
let _avatar = avatar;
if (!avatar.includes('http')) {
_avatar = baseConfig.HTTP_REQUEST_URL + _avatar;
}
return {
...args,
avatar: _avatar
};
}
const getBaseUserInfo = () => {
const userInfo = utils.getStorage(USER_INFO_KEY);
if (userInfo.uid) return userInfo;
return {};
}
const getToken = () => {
return utils.getStorage(TOKEN_KEY);
}
export default {
namespaced: true,
state() {
return {
isLogin: !!getToken(),
token: getToken(),
userInfo: getBaseUserInfo(),
rootFontSize: "50px"
}
},
mutations: {
[SET_LOGIN](state, { userInfo, token }) {
state.userInfo = mergeUserInfo(userInfo);
state.isLogin = true;
state.token = token;
utils.setStorage(TOKEN_KEY, token);
utils.setStorage(USER_INFO_KEY, state.userInfo);
},
[SET_LOGOUT](state) {
state.isLogin = false;
state.token = null;
state.userInfo = {};
utils.removeStorage(TOKEN_KEY);
utils.removeStorage(USER_INFO_KEY);
},
[UPDATE_USER_INFO](state, userInfo) {
state.userInfo = mergeUserInfo(userInfo);
utils.setStorage(USER_INFO_KEY, state.userInfo);
},
[SET_ROOT_FONT](state, { isInit = false }) {
const setRemUnit = () => {
const { width } = uni.getSystemInfoSync().safeArea;
state.rootFontSize = width / 7.5 + "px";
}
setRemUnit();
isInit && uni.onWindowResize(() => {
setRemUnit();
});
}
},
actions: {
async [VALID_LOGIN_STATUS]({ commit }) {
try {
const { data } = await validLoginStatus();
commit(UPDATE_USER_INFO, data);
} catch (err) {
commit(SET_LOGOUT);
// console.log(err);
}
}
}
}