初始版本提交
This commit is contained in:
10
src/store/index.ts
Normal file
10
src/store/index.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import type { App } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
|
||||
const store = createPinia();
|
||||
|
||||
export function setupStore(app: App<Element>) {
|
||||
app.use(store);
|
||||
}
|
||||
|
||||
export { store };
|
||||
118
src/store/modules/app.ts
Normal file
118
src/store/modules/app.ts
Normal file
@ -0,0 +1,118 @@
|
||||
import type {
|
||||
ProjectConfig,
|
||||
HeaderSetting,
|
||||
MenuSetting,
|
||||
TransitionSetting,
|
||||
MultiTabsSetting,
|
||||
LogoConfig,
|
||||
} from '/#/config';
|
||||
import type { BeforeMiniState } from '/#/store';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
import { store } from '/@/store';
|
||||
|
||||
import { ThemeEnum } from '/@/enums/appEnum';
|
||||
import { APP_DARK_MODE_KEY_, PROJ_CFG_KEY } from '/@/enums/cacheEnum';
|
||||
import { Persistent } from '/@/utils/cache/persistent';
|
||||
import { darkMode } from '/@/settings/designSetting';
|
||||
import { resetRouter } from '/@/router';
|
||||
import { deepMerge } from '/@/utils';
|
||||
|
||||
interface AppState {
|
||||
darkMode?: ThemeEnum;
|
||||
// Page loading status
|
||||
pageLoading: boolean;
|
||||
// project config
|
||||
projectConfig: ProjectConfig | null;
|
||||
// When the window shrinks, remember some states, and restore these states when the window is restored
|
||||
beforeMiniInfo: BeforeMiniState;
|
||||
logoConfig: LogoConfig;
|
||||
}
|
||||
let timeId: TimeoutHandle;
|
||||
export const useAppStore = defineStore({
|
||||
id: 'app',
|
||||
state: (): AppState => ({
|
||||
darkMode: undefined,
|
||||
pageLoading: false,
|
||||
projectConfig: Persistent.getLocal(PROJ_CFG_KEY),
|
||||
beforeMiniInfo: {},
|
||||
logoConfig: {} as LogoConfig,
|
||||
}),
|
||||
getters: {
|
||||
getPageLoading(): boolean {
|
||||
return this.pageLoading;
|
||||
},
|
||||
getDarkMode(): 'light' | 'dark' | string {
|
||||
return this.darkMode || localStorage.getItem(APP_DARK_MODE_KEY_) || darkMode;
|
||||
},
|
||||
|
||||
getBeforeMiniInfo(): BeforeMiniState {
|
||||
return this.beforeMiniInfo;
|
||||
},
|
||||
|
||||
getProjectConfig(): ProjectConfig {
|
||||
return this.projectConfig || ({} as ProjectConfig);
|
||||
},
|
||||
|
||||
getHeaderSetting(): HeaderSetting {
|
||||
return this.getProjectConfig.headerSetting;
|
||||
},
|
||||
getMenuSetting(): MenuSetting {
|
||||
return this.getProjectConfig.menuSetting;
|
||||
},
|
||||
getTransitionSetting(): TransitionSetting {
|
||||
return this.getProjectConfig.transitionSetting;
|
||||
},
|
||||
getMultiTabsSetting(): MultiTabsSetting {
|
||||
return this.getProjectConfig.multiTabsSetting;
|
||||
},
|
||||
getLogoConfig(): LogoConfig {
|
||||
return this.logoConfig;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
setPageLoading(loading: boolean): void {
|
||||
this.pageLoading = loading;
|
||||
},
|
||||
|
||||
setDarkMode(mode: ThemeEnum): void {
|
||||
this.darkMode = mode;
|
||||
localStorage.setItem(APP_DARK_MODE_KEY_, mode);
|
||||
},
|
||||
|
||||
setBeforeMiniInfo(state: BeforeMiniState): void {
|
||||
this.beforeMiniInfo = state;
|
||||
},
|
||||
|
||||
setProjectConfig(config: DeepPartial<ProjectConfig>): void {
|
||||
this.projectConfig = deepMerge(this.projectConfig || {}, config);
|
||||
Persistent.setLocal(PROJ_CFG_KEY, this.projectConfig);
|
||||
},
|
||||
|
||||
async resetAllState() {
|
||||
resetRouter();
|
||||
Persistent.clearAll();
|
||||
},
|
||||
async setPageLoadingAction(loading: boolean): Promise<void> {
|
||||
if (loading) {
|
||||
clearTimeout(timeId);
|
||||
// Prevent flicker
|
||||
timeId = setTimeout(() => {
|
||||
this.setPageLoading(loading);
|
||||
}, 50);
|
||||
} else {
|
||||
this.setPageLoading(loading);
|
||||
clearTimeout(timeId);
|
||||
}
|
||||
},
|
||||
|
||||
setLogoConfig(config: LogoConfig): void {
|
||||
this.logoConfig = config;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Need to be used outside the setup
|
||||
export function useAppStoreWithOut() {
|
||||
return useAppStore(store);
|
||||
}
|
||||
77
src/store/modules/errorLog.ts
Normal file
77
src/store/modules/errorLog.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import type { ErrorLogInfo } from '/#/store';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
import { store } from '/@/store';
|
||||
|
||||
import { formatToDateTime } from '/@/utils/dateUtil';
|
||||
import projectSetting from '/@/settings/projectSetting';
|
||||
|
||||
import { ErrorTypeEnum } from '/@/enums/exceptionEnum';
|
||||
|
||||
export interface ErrorLogState {
|
||||
errorLogInfoList: Nullable<ErrorLogInfo[]>;
|
||||
errorLogListCount: number;
|
||||
}
|
||||
|
||||
export const useErrorLogStore = defineStore({
|
||||
id: 'app-error-log',
|
||||
state: (): ErrorLogState => ({
|
||||
errorLogInfoList: null,
|
||||
errorLogListCount: 0,
|
||||
}),
|
||||
getters: {
|
||||
getErrorLogInfoList(): ErrorLogInfo[] {
|
||||
return this.errorLogInfoList || [];
|
||||
},
|
||||
getErrorLogListCount(): number {
|
||||
return this.errorLogListCount;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
addErrorLogInfo(info: ErrorLogInfo) {
|
||||
const item = {
|
||||
...info,
|
||||
time: formatToDateTime(new Date()),
|
||||
};
|
||||
this.errorLogInfoList = [item, ...(this.errorLogInfoList || [])];
|
||||
this.errorLogListCount += 1;
|
||||
},
|
||||
|
||||
setErrorLogListCount(count: number): void {
|
||||
this.errorLogListCount = count;
|
||||
},
|
||||
|
||||
/**
|
||||
* Triggered after ajax request error
|
||||
* @param error
|
||||
* @returns
|
||||
*/
|
||||
addAjaxErrorInfo(error) {
|
||||
const { useErrorHandle } = projectSetting;
|
||||
if (!useErrorHandle) {
|
||||
return;
|
||||
}
|
||||
const errInfo: Partial<ErrorLogInfo> = {
|
||||
message: error.message,
|
||||
type: ErrorTypeEnum.AJAX,
|
||||
};
|
||||
if (error.response) {
|
||||
const {
|
||||
config: { url = '', data: params = '', method = 'get', headers = {} } = {},
|
||||
data = {},
|
||||
} = error.response;
|
||||
errInfo.url = url;
|
||||
errInfo.name = 'Ajax Error!';
|
||||
errInfo.file = '-';
|
||||
errInfo.stack = JSON.stringify(data);
|
||||
errInfo.detail = JSON.stringify({ params, method, headers });
|
||||
}
|
||||
this.addErrorLogInfo(errInfo as ErrorLogInfo);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Need to be used outside the setup
|
||||
export function useErrorLogStoreWithOut() {
|
||||
return useErrorLogStore(store);
|
||||
}
|
||||
68
src/store/modules/locale.ts
Normal file
68
src/store/modules/locale.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import type { LocaleSetting, LocaleType } from '/#/config';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
import { store } from '/@/store';
|
||||
|
||||
import { LANGUAGE_KEY, LOCALE_KEY } from '/@/enums/cacheEnum';
|
||||
import { createLocalStorage } from '/@/utils/cache';
|
||||
import { localeSetting } from '/@/settings/localeSetting';
|
||||
|
||||
const ls = createLocalStorage();
|
||||
|
||||
const lsLocaleSetting = (ls.get(LOCALE_KEY) || localeSetting) as LocaleSetting;
|
||||
|
||||
interface LocaleState {
|
||||
localInfo: LocaleSetting;
|
||||
languageJson: Recordable;
|
||||
}
|
||||
|
||||
export const useLocaleStore = defineStore({
|
||||
id: 'app-locale',
|
||||
state: (): LocaleState => ({
|
||||
localInfo: lsLocaleSetting,
|
||||
languageJson: {},
|
||||
}),
|
||||
getters: {
|
||||
getShowPicker(): boolean {
|
||||
return !!this.localInfo?.showPicker;
|
||||
},
|
||||
getLocale(): LocaleType {
|
||||
return this.localInfo?.locale ?? 'zh_CN';
|
||||
},
|
||||
getLanguageJson(): Recordable {
|
||||
return this.languageJson;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
/**
|
||||
* Set up multilingual information and cache
|
||||
* @param info multilingual info
|
||||
*/
|
||||
setLanguageJson(json: Recordable) {
|
||||
this.languageJson = json;
|
||||
ls.set(LANGUAGE_KEY, this.languageJson);
|
||||
},
|
||||
/**
|
||||
* Set up multilingual information and cache
|
||||
* @param info multilingual info
|
||||
*/
|
||||
setLocaleInfo(info: Partial<LocaleSetting>) {
|
||||
this.localInfo = { ...this.localInfo, ...info };
|
||||
ls.set(LOCALE_KEY, this.localInfo);
|
||||
},
|
||||
/**
|
||||
* Initialize multilingual information and load the existing configuration from the local cache
|
||||
*/
|
||||
initLocale() {
|
||||
this.setLocaleInfo({
|
||||
...localeSetting,
|
||||
...this.localInfo,
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Need to be used outside the setup
|
||||
export function useLocaleStoreWithOut() {
|
||||
return useLocaleStore(store);
|
||||
}
|
||||
59
src/store/modules/lock.ts
Normal file
59
src/store/modules/lock.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import type { LockInfo } from '/#/store';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import { LOCK_INFO_KEY } from '/@/enums/cacheEnum';
|
||||
import { Persistent } from '/@/utils/cache/persistent';
|
||||
import { useUserStore } from './user';
|
||||
|
||||
interface LockState {
|
||||
lockInfo: Nullable<LockInfo>;
|
||||
}
|
||||
|
||||
export const useLockStore = defineStore({
|
||||
id: 'app-lock',
|
||||
state: (): LockState => ({
|
||||
lockInfo: Persistent.getLocal(LOCK_INFO_KEY),
|
||||
}),
|
||||
getters: {
|
||||
getLockInfo(): Nullable<LockInfo> {
|
||||
return this.lockInfo;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
setLockInfo(info: LockInfo) {
|
||||
this.lockInfo = Object.assign({}, this.lockInfo, info);
|
||||
Persistent.setLocal(LOCK_INFO_KEY, this.lockInfo, true);
|
||||
},
|
||||
resetLockInfo() {
|
||||
Persistent.removeLocal(LOCK_INFO_KEY, true);
|
||||
this.lockInfo = null;
|
||||
},
|
||||
// Unlock
|
||||
async unLock(password?: string) {
|
||||
const userStore = useUserStore();
|
||||
if (this.lockInfo?.pwd === password) {
|
||||
this.resetLockInfo();
|
||||
return true;
|
||||
}
|
||||
const tryLogin = async () => {
|
||||
try {
|
||||
const userName = userStore.getUserInfo?.userName;
|
||||
const res = await userStore.login({
|
||||
userName,
|
||||
password: password!,
|
||||
goHome: false,
|
||||
mode: 'none',
|
||||
});
|
||||
if (res) {
|
||||
this.resetLockInfo();
|
||||
}
|
||||
return res;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
return await tryLogin();
|
||||
},
|
||||
},
|
||||
});
|
||||
359
src/store/modules/multipleTab.ts
Normal file
359
src/store/modules/multipleTab.ts
Normal file
@ -0,0 +1,359 @@
|
||||
import type { RouteLocationNormalized, RouteLocationRaw, Router } from 'vue-router';
|
||||
|
||||
import { toRaw, unref } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
import { store } from '/@/store';
|
||||
|
||||
import { useGo, useRedo } from '/@/hooks/web/usePage';
|
||||
import { Persistent } from '/@/utils/cache/persistent';
|
||||
|
||||
import { PageEnum } from '/@/enums/pageEnum';
|
||||
import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '/@/router/routes/basic';
|
||||
import { getRawRoute } from '/@/utils';
|
||||
import { MULTIPLE_TABS_KEY } from '/@/enums/cacheEnum';
|
||||
|
||||
import projectSetting from '/@/settings/projectSetting';
|
||||
import { useUserStore } from '/@/store/modules/user';
|
||||
|
||||
export interface MultipleTabState {
|
||||
cacheTabList: Set<string>;
|
||||
tabList: RouteLocationNormalized[];
|
||||
lastDragEndIndex: number;
|
||||
}
|
||||
|
||||
function handleGotoPage(router: Router) {
|
||||
const go = useGo(router);
|
||||
go(unref(router.currentRoute).path, true);
|
||||
}
|
||||
|
||||
const getToTarget = (tabItem: RouteLocationNormalized) => {
|
||||
const { params, path, query } = tabItem;
|
||||
return {
|
||||
params: params || {},
|
||||
path,
|
||||
query: query || {},
|
||||
};
|
||||
};
|
||||
|
||||
const cacheTab = projectSetting.multiTabsSetting.cache;
|
||||
|
||||
export const useMultipleTabStore = defineStore({
|
||||
id: 'app-multiple-tab',
|
||||
state: (): MultipleTabState => ({
|
||||
// Tabs that need to be cached
|
||||
cacheTabList: new Set(),
|
||||
// multiple tab list
|
||||
tabList: cacheTab ? Persistent.getLocal(MULTIPLE_TABS_KEY) || [] : [],
|
||||
// Index of the last moved tab
|
||||
lastDragEndIndex: 0,
|
||||
}),
|
||||
getters: {
|
||||
getTabList(): RouteLocationNormalized[] {
|
||||
return this.tabList;
|
||||
},
|
||||
getCachedTabList(): string[] {
|
||||
return Array.from(this.cacheTabList);
|
||||
},
|
||||
getLastDragEndIndex(): number {
|
||||
return this.lastDragEndIndex;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
/**
|
||||
* Update the cache according to the currently opened tabs
|
||||
*/
|
||||
async updateCacheTab() {
|
||||
const cacheMap: Set<string> = new Set();
|
||||
|
||||
for (const tab of this.tabList) {
|
||||
const item = getRawRoute(tab);
|
||||
// Ignore the cache
|
||||
const needCache = !item.meta?.ignoreKeepAlive;
|
||||
if (!needCache) {
|
||||
continue;
|
||||
}
|
||||
const name = item.name as string;
|
||||
cacheMap.add(name);
|
||||
}
|
||||
this.cacheTabList = cacheMap;
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh tabs
|
||||
*/
|
||||
async refreshPage(router: Router) {
|
||||
const { currentRoute } = router;
|
||||
const route = unref(currentRoute);
|
||||
const name = route.name;
|
||||
|
||||
const findTab = this.getCachedTabList.find((item) => item === name);
|
||||
if (findTab) {
|
||||
this.cacheTabList.delete(findTab);
|
||||
}
|
||||
const redo = useRedo(router);
|
||||
await redo();
|
||||
},
|
||||
clearCacheTabs(): void {
|
||||
this.cacheTabList = new Set();
|
||||
},
|
||||
resetState(): void {
|
||||
this.tabList = [];
|
||||
this.clearCacheTabs();
|
||||
},
|
||||
goToPage(router: Router) {
|
||||
const go = useGo(router);
|
||||
const len = this.tabList.length;
|
||||
const { path } = unref(router.currentRoute);
|
||||
|
||||
let toPath: PageEnum | string = PageEnum.BASE_HOME;
|
||||
|
||||
if (len > 0) {
|
||||
const page = this.tabList[len - 1];
|
||||
const p = page.fullPath || page.path;
|
||||
if (p) {
|
||||
toPath = p;
|
||||
}
|
||||
}
|
||||
// Jump to the current page and report an error
|
||||
path !== toPath && go(toPath as PageEnum, true);
|
||||
},
|
||||
|
||||
async addTab(route: RouteLocationNormalized) {
|
||||
const { path, name, fullPath, params, query, meta } = getRawRoute(route);
|
||||
// 404 The page does not need to add a tab
|
||||
if (
|
||||
path === PageEnum.ERROR_PAGE ||
|
||||
path === PageEnum.BASE_LOGIN ||
|
||||
!name ||
|
||||
[REDIRECT_ROUTE.name, PAGE_NOT_FOUND_ROUTE.name].includes(name as string)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let updateIndex = -1;
|
||||
// Existing pages, do not add tabs repeatedly
|
||||
const tabHasExits = this.tabList.some((tab, index) => {
|
||||
updateIndex = index;
|
||||
return (tab.fullPath || tab.path) === (fullPath || path);
|
||||
});
|
||||
|
||||
// If the tab already exists, perform the update operation
|
||||
if (tabHasExits) {
|
||||
const curTab = toRaw(this.tabList)[updateIndex];
|
||||
if (!curTab) {
|
||||
return;
|
||||
}
|
||||
curTab.params = params || curTab.params;
|
||||
curTab.query = query || curTab.query;
|
||||
curTab.fullPath = fullPath || curTab.fullPath;
|
||||
this.tabList.splice(updateIndex, 1, curTab);
|
||||
} else {
|
||||
// Add tab
|
||||
// 获取动态路由打开数,超过 0 即代表需要控制打开数
|
||||
const dynamicLevel = meta?.dynamicLevel ?? -1;
|
||||
if (dynamicLevel > 0) {
|
||||
// 如果动态路由层级大于 0 了,那么就要限制该路由的打开数限制了
|
||||
// 首先获取到真实的路由,使用配置方式减少计算开销.
|
||||
// const realName: string = path.match(/(\S*)\//)![1];
|
||||
const realPath = meta?.realPath ?? '';
|
||||
// 获取到已经打开的动态路由数, 判断是否大于某一个值
|
||||
if (
|
||||
this.tabList.filter((e) => e.meta?.realPath ?? '' === realPath).length >= dynamicLevel
|
||||
) {
|
||||
// 关闭第一个
|
||||
const index = this.tabList.findIndex((item) => item.meta.realPath === realPath);
|
||||
index !== -1 && this.tabList.splice(index, 1);
|
||||
}
|
||||
}
|
||||
this.tabList.push(route);
|
||||
}
|
||||
this.updateCacheTab();
|
||||
cacheTab && Persistent.setLocal(MULTIPLE_TABS_KEY, this.tabList);
|
||||
},
|
||||
|
||||
async closeTab(tab: RouteLocationNormalized, router: Router) {
|
||||
const close = (route: RouteLocationNormalized) => {
|
||||
const { fullPath, meta: { affix } = {} } = route;
|
||||
if (affix) {
|
||||
return;
|
||||
}
|
||||
const index = this.tabList.findIndex((item) => item.fullPath === fullPath);
|
||||
index !== -1 && this.tabList.splice(index, 1);
|
||||
};
|
||||
|
||||
const { currentRoute, replace } = router;
|
||||
|
||||
const { path } = unref(currentRoute);
|
||||
if (path !== tab.path) {
|
||||
// Closed is not the activation tab
|
||||
close(tab);
|
||||
return;
|
||||
}
|
||||
|
||||
// Closed is activated atb
|
||||
let toTarget: RouteLocationRaw = {};
|
||||
|
||||
const index = this.tabList.findIndex((item) => item.path === path);
|
||||
|
||||
// If the current is the leftmost tab
|
||||
if (index === 0) {
|
||||
// There is only one tab, then jump to the homepage, otherwise jump to the right tab
|
||||
if (this.tabList.length === 1) {
|
||||
const userStore = useUserStore();
|
||||
toTarget = userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
|
||||
} else {
|
||||
// Jump to the right tab
|
||||
const page = this.tabList[index + 1];
|
||||
toTarget = getToTarget(page);
|
||||
}
|
||||
} else {
|
||||
// Close the current tab
|
||||
const page = this.tabList[index - 1];
|
||||
toTarget = getToTarget(page);
|
||||
}
|
||||
close(currentRoute.value);
|
||||
await replace(toTarget);
|
||||
},
|
||||
|
||||
// Close according to key
|
||||
async closeTabByKey(key: string, router: Router) {
|
||||
const index = this.tabList.findIndex((item) => (item.fullPath || item.path) === key);
|
||||
if (index !== -1) {
|
||||
await this.closeTab(this.tabList[index], router);
|
||||
const { currentRoute, replace } = router;
|
||||
// 检查当前路由是否存在于tabList中
|
||||
const isActivated = this.tabList.findIndex((item) => {
|
||||
return item.fullPath === currentRoute.value.fullPath;
|
||||
});
|
||||
// 如果当前路由不存在于TabList中,尝试切换到其它路由
|
||||
if (isActivated === -1) {
|
||||
let pageIndex;
|
||||
if (index > 0) {
|
||||
pageIndex = index - 1;
|
||||
} else if (index < this.tabList.length - 1) {
|
||||
pageIndex = index + 1;
|
||||
} else {
|
||||
pageIndex = -1;
|
||||
}
|
||||
if (pageIndex >= 0) {
|
||||
const page = this.tabList[index - 1];
|
||||
const toTarget = getToTarget(page);
|
||||
await replace(toTarget);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Sort the tabs
|
||||
async sortTabs(oldIndex: number, newIndex: number) {
|
||||
const currentTab = this.tabList[oldIndex];
|
||||
this.tabList.splice(oldIndex, 1);
|
||||
this.tabList.splice(newIndex, 0, currentTab);
|
||||
this.lastDragEndIndex = this.lastDragEndIndex + 1;
|
||||
},
|
||||
|
||||
// Close the tab on the right and jump
|
||||
async closeLeftTabs(route: RouteLocationNormalized, router: Router) {
|
||||
const index = this.tabList.findIndex((item) => item.path === route.path);
|
||||
|
||||
if (index > 0) {
|
||||
const leftTabs = this.tabList.slice(0, index);
|
||||
const pathList: string[] = [];
|
||||
for (const item of leftTabs) {
|
||||
const affix = item?.meta?.affix ?? false;
|
||||
if (!affix) {
|
||||
pathList.push(item.fullPath);
|
||||
}
|
||||
}
|
||||
this.bulkCloseTabs(pathList);
|
||||
}
|
||||
this.updateCacheTab();
|
||||
handleGotoPage(router);
|
||||
},
|
||||
|
||||
// Close the tab on the left and jump
|
||||
async closeRightTabs(route: RouteLocationNormalized, router: Router) {
|
||||
const index = this.tabList.findIndex((item) => item.fullPath === route.fullPath);
|
||||
|
||||
if (index >= 0 && index < this.tabList.length - 1) {
|
||||
const rightTabs = this.tabList.slice(index + 1, this.tabList.length);
|
||||
|
||||
const pathList: string[] = [];
|
||||
for (const item of rightTabs) {
|
||||
const affix = item?.meta?.affix ?? false;
|
||||
if (!affix) {
|
||||
pathList.push(item.fullPath);
|
||||
}
|
||||
}
|
||||
this.bulkCloseTabs(pathList);
|
||||
}
|
||||
this.updateCacheTab();
|
||||
handleGotoPage(router);
|
||||
},
|
||||
|
||||
async closeAllTab(router: Router) {
|
||||
this.tabList = this.tabList.filter((item) => item?.meta?.affix ?? false);
|
||||
this.clearCacheTabs();
|
||||
this.goToPage(router);
|
||||
},
|
||||
|
||||
/**
|
||||
* Close other tabs
|
||||
*/
|
||||
async closeOtherTabs(route: RouteLocationNormalized, router: Router) {
|
||||
const closePathList = this.tabList.map((item) => item.fullPath);
|
||||
|
||||
const pathList: string[] = [];
|
||||
|
||||
for (const path of closePathList) {
|
||||
if (path !== route.fullPath) {
|
||||
const closeItem = this.tabList.find((item) => item.path === path);
|
||||
if (!closeItem) {
|
||||
continue;
|
||||
}
|
||||
const affix = closeItem?.meta?.affix ?? false;
|
||||
if (!affix) {
|
||||
pathList.push(closeItem.fullPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.bulkCloseTabs(pathList);
|
||||
this.updateCacheTab();
|
||||
handleGotoPage(router);
|
||||
},
|
||||
|
||||
/**
|
||||
* Close tabs in bulk
|
||||
*/
|
||||
async bulkCloseTabs(pathList: string[]) {
|
||||
this.tabList = this.tabList.filter((item) => !pathList.includes(item.fullPath));
|
||||
},
|
||||
|
||||
/**
|
||||
* Set tab's title
|
||||
*/
|
||||
async setTabTitle(title: string, route: RouteLocationNormalized) {
|
||||
const findTab = this.getTabList.find((item) => item === route);
|
||||
if (findTab) {
|
||||
findTab.meta.title = title;
|
||||
await this.updateCacheTab();
|
||||
}
|
||||
},
|
||||
/**
|
||||
* replace tab's path
|
||||
* **/
|
||||
async updateTabPath(fullPath: string, route: RouteLocationNormalized) {
|
||||
const findTab = this.getTabList.find((item) => item === route);
|
||||
if (findTab) {
|
||||
findTab.fullPath = fullPath;
|
||||
findTab.path = fullPath;
|
||||
await this.updateCacheTab();
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Need to be used outside the setup
|
||||
export function useMultipleTabWithOutStore() {
|
||||
return useMultipleTabStore(store);
|
||||
}
|
||||
267
src/store/modules/permission.ts
Normal file
267
src/store/modules/permission.ts
Normal file
@ -0,0 +1,267 @@
|
||||
import type { AppRouteRecordRaw, Menu, subSys } from '/@/router/types';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
import { store } from '/@/store';
|
||||
import { useI18n } from '/@/hooks/web/useI18n';
|
||||
import { useUserStore } from './user';
|
||||
import { useAppStoreWithOut } from './app';
|
||||
import { toRaw } from 'vue';
|
||||
import { transformObjToRoute, flatMultiLevelRoutes } from '/@/router/helper/routeHelper';
|
||||
import { transformRouteToMenu } from '/@/router/helper/menuHelper';
|
||||
|
||||
import projectSetting from '/@/settings/projectSetting';
|
||||
|
||||
import { PermissionModeEnum } from '/@/enums/appEnum';
|
||||
|
||||
import { asyncRoutes } from '/@/router/routes';
|
||||
import { ERROR_LOG_ROUTE, PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
|
||||
|
||||
import { filter } from '/@/utils/helper/treeHelper';
|
||||
|
||||
import { useMessage } from '/@/hooks/web/useMessage';
|
||||
import { PageEnum } from '/@/enums/pageEnum';
|
||||
import { getMenuList, getPermCode } from '/@/api/system/login';
|
||||
import { MenuAuthModel } from '/@/api/system/login/model';
|
||||
import { getSubSystemList } from '/@/api/system/subSystem';
|
||||
|
||||
interface PermissionState {
|
||||
// Permission code list
|
||||
permCodeList: MenuAuthModel[];
|
||||
// Whether the route has been dynamically added
|
||||
isDynamicAddedRoute: boolean;
|
||||
// To trigger a menu update
|
||||
lastBuildMenuTime: number;
|
||||
// Backstage menu list
|
||||
backMenuList: Menu[];
|
||||
frontMenuList: Menu[];
|
||||
subSystem: string;
|
||||
subSystemList: subSys[];
|
||||
}
|
||||
export const usePermissionStore = defineStore({
|
||||
id: 'app-permission',
|
||||
state: (): PermissionState => ({
|
||||
permCodeList: [],
|
||||
// Whether the route has been dynamically added
|
||||
isDynamicAddedRoute: false,
|
||||
// To trigger a menu update
|
||||
lastBuildMenuTime: 0,
|
||||
// Backstage menu list
|
||||
backMenuList: [],
|
||||
// menu List
|
||||
frontMenuList: [],
|
||||
//sub system
|
||||
subSystem: '1',
|
||||
subSystemList: [],
|
||||
}),
|
||||
getters: {
|
||||
getPermCodeList(): MenuAuthModel[] {
|
||||
return this.permCodeList || [];
|
||||
},
|
||||
getBackMenuList(): Menu[] {
|
||||
return this.backMenuList.filter((item) => this.getSubSystem === item.meta!.systemId);
|
||||
},
|
||||
getFrontMenuList(): Menu[] {
|
||||
return this.frontMenuList;
|
||||
},
|
||||
getLastBuildMenuTime(): number {
|
||||
return this.lastBuildMenuTime;
|
||||
},
|
||||
getIsDynamicAddedRoute(): boolean {
|
||||
return this.isDynamicAddedRoute;
|
||||
},
|
||||
getSubSystem(): string {
|
||||
return this.subSystem;
|
||||
},
|
||||
getSubSysList(): subSys[] {
|
||||
return this.subSystemList;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
setPermCodeList(permList: MenuAuthModel[]) {
|
||||
this.permCodeList = permList;
|
||||
},
|
||||
|
||||
setBackMenuList(list: Menu[]) {
|
||||
this.backMenuList = list;
|
||||
list?.length > 0 && this.setLastBuildMenuTime();
|
||||
},
|
||||
|
||||
setFrontMenuList(list: Menu[]) {
|
||||
this.frontMenuList = list;
|
||||
},
|
||||
|
||||
setLastBuildMenuTime() {
|
||||
this.lastBuildMenuTime = new Date().getTime();
|
||||
},
|
||||
|
||||
setDynamicAddedRoute(added: boolean) {
|
||||
this.isDynamicAddedRoute = added;
|
||||
},
|
||||
setSubSystem(systemId: string) {
|
||||
this.subSystem = systemId;
|
||||
},
|
||||
setSubSystemList(subSystemList: subSys[]) {
|
||||
this.subSystemList = subSystemList;
|
||||
},
|
||||
resetState(): void {
|
||||
this.isDynamicAddedRoute = false;
|
||||
this.permCodeList = [];
|
||||
this.backMenuList = [];
|
||||
this.lastBuildMenuTime = 0;
|
||||
},
|
||||
async changeSubsystem(getShowTopMenu, getIsMobile) {
|
||||
const arr = await getSubSystemList();
|
||||
let subSystemList: any = [];
|
||||
if (getShowTopMenu && !getIsMobile) {
|
||||
arr.forEach((o) => {
|
||||
subSystemList.push({
|
||||
text: o.name,
|
||||
event: o.id,
|
||||
icon: o.icon,
|
||||
});
|
||||
});
|
||||
} else {
|
||||
subSystemList = arr;
|
||||
}
|
||||
this.setSubSystemList(subSystemList);
|
||||
},
|
||||
async changePermissionCode() {
|
||||
const userStore = useUserStore();
|
||||
const userInfo = userStore.getUserInfo;
|
||||
|
||||
const permResult = await getPermCode();
|
||||
|
||||
userInfo.departmentId = permResult.departmentId;
|
||||
userInfo.departmentName = permResult.departmentName;
|
||||
userInfo.postId = permResult.postId;
|
||||
userInfo.postName = permResult.postName;
|
||||
userInfo.desktopSchema = permResult.desktopSchema;
|
||||
|
||||
userStore.setUserInfo(userInfo);
|
||||
this.setPermCodeList(permResult.menuAuthList);
|
||||
},
|
||||
async buildRoutesAction(isRefrashPermisson = true): Promise<AppRouteRecordRaw[]> {
|
||||
const { t } = useI18n();
|
||||
const userStore = useUserStore();
|
||||
const appStore = useAppStoreWithOut();
|
||||
|
||||
let routes: AppRouteRecordRaw[] = [];
|
||||
const roleList = toRaw(userStore.getRoleList) || [];
|
||||
const { permissionMode = projectSetting.permissionMode } = appStore.getProjectConfig;
|
||||
|
||||
const routeFilter = (route: AppRouteRecordRaw) => {
|
||||
const { meta } = route;
|
||||
const { roles } = meta || {};
|
||||
if (!roles) return true;
|
||||
return roleList.some((role) => roles.includes(role));
|
||||
};
|
||||
|
||||
const routeRemoveIgnoreFilter = (route: AppRouteRecordRaw) => {
|
||||
const { meta } = route;
|
||||
const { ignoreRoute } = meta || {};
|
||||
return !ignoreRoute;
|
||||
};
|
||||
|
||||
/**
|
||||
* @description 根据设置的首页path,修正routes中的affix标记(固定首页)
|
||||
* */
|
||||
const patchHomeAffix = (routes: AppRouteRecordRaw[]) => {
|
||||
if (!routes || routes.length === 0) return;
|
||||
let homePath: string = userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
|
||||
function patcher(routes: AppRouteRecordRaw[], parentPath = '') {
|
||||
if (parentPath) parentPath = parentPath + '/';
|
||||
routes.forEach((route: AppRouteRecordRaw) => {
|
||||
const { path, children, redirect } = route;
|
||||
const currentPath = path.startsWith('/') ? path : parentPath + path;
|
||||
if (currentPath === homePath) {
|
||||
if (redirect) {
|
||||
homePath = route.redirect! as string;
|
||||
} else {
|
||||
route.meta = Object.assign({}, route.meta, { affix: true });
|
||||
throw new Error('end');
|
||||
}
|
||||
}
|
||||
children && children.length > 0 && patcher(children, currentPath);
|
||||
});
|
||||
}
|
||||
try {
|
||||
patcher(routes);
|
||||
} catch (e) {
|
||||
// 已处理完毕跳出循环
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
switch (permissionMode) {
|
||||
case PermissionModeEnum.ROLE:
|
||||
routes = filter(asyncRoutes, routeFilter);
|
||||
routes = routes.filter(routeFilter);
|
||||
// Convert multi-level routing to level 2 routing
|
||||
routes = flatMultiLevelRoutes(routes);
|
||||
break;
|
||||
|
||||
case PermissionModeEnum.ROUTE_MAPPING:
|
||||
routes = filter(asyncRoutes, routeFilter);
|
||||
routes = routes.filter(routeFilter);
|
||||
const menuList = transformRouteToMenu(routes, true);
|
||||
routes = filter(routes, routeRemoveIgnoreFilter);
|
||||
routes = routes.filter(routeRemoveIgnoreFilter);
|
||||
menuList.sort((a, b) => {
|
||||
return (a.meta?.orderNo || 0) - (b.meta?.orderNo || 0);
|
||||
});
|
||||
|
||||
this.setFrontMenuList(menuList);
|
||||
// Convert multi-level routing to level 2 routing
|
||||
routes = flatMultiLevelRoutes(routes);
|
||||
break;
|
||||
|
||||
// If you are sure that you do not need to do background dynamic permissions, please comment the entire judgment below
|
||||
case PermissionModeEnum.BACK:
|
||||
const { createMessage } = useMessage();
|
||||
|
||||
createMessage.loading({
|
||||
content: t('菜单加载中...'),
|
||||
duration: 1,
|
||||
});
|
||||
|
||||
// !Simulate to obtain permission codes from the background,
|
||||
// this function may only need to be executed once, and the actual project can be put at the right time by itself
|
||||
let routeList: AppRouteRecordRaw[] = [];
|
||||
try {
|
||||
if (isRefrashPermisson) await this.changePermissionCode();
|
||||
|
||||
routeList = (await getMenuList()) as AppRouteRecordRaw[];
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
// Dynamically introduce components
|
||||
routeList = transformObjToRoute(routeList);
|
||||
|
||||
// Background routing to menu structure
|
||||
const backMenuList = transformRouteToMenu(routeList);
|
||||
|
||||
this.setBackMenuList(backMenuList);
|
||||
|
||||
// remove meta.ignoreRoute item
|
||||
routeList = filter(routeList, routeRemoveIgnoreFilter);
|
||||
routeList = routeList.filter(routeRemoveIgnoreFilter);
|
||||
|
||||
routeList = flatMultiLevelRoutes(routeList);
|
||||
|
||||
routes = [PAGE_NOT_FOUND_ROUTE, ...routeList];
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
routes.push(ERROR_LOG_ROUTE);
|
||||
patchHomeAffix(routes);
|
||||
return routes;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Need to be used outside the setup
|
||||
export function usePermissionStoreWithOut() {
|
||||
return usePermissionStore(store);
|
||||
}
|
||||
229
src/store/modules/user.ts
Normal file
229
src/store/modules/user.ts
Normal file
@ -0,0 +1,229 @@
|
||||
import type { UserInfo } from '/#/store';
|
||||
import type { ErrorMessageMode } from '/#/axios';
|
||||
import { defineStore } from 'pinia';
|
||||
import { store } from '/@/store';
|
||||
import { PageEnum } from '/@/enums/pageEnum';
|
||||
import { ROLES_KEY, TOKEN_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum';
|
||||
import { getAuthCache, setAuthCache } from '/@/utils/auth';
|
||||
import { GetUserInfoModel, LoginParams, RoleInfo } from '/@/api/system/login/model';
|
||||
import { doLogout, getUserInfo, loginApi } from '/@/api/system/login';
|
||||
import { useI18n } from '/@/hooks/web/useI18n';
|
||||
import { useMessage } from '/@/hooks/web/useMessage';
|
||||
import { router } from '/@/router';
|
||||
import { usePermissionStore } from '/@/store/modules/permission';
|
||||
import { RouteRecordRaw } from 'vue-router';
|
||||
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
|
||||
import { h } from 'vue';
|
||||
import { getAppEnvConfig } from '/@/utils/env';
|
||||
interface UserState {
|
||||
userInfo: Nullable<UserInfo>;
|
||||
token?: string;
|
||||
roleList: RoleInfo[];
|
||||
sessionTimeout?: boolean;
|
||||
lastUpdateTime: number;
|
||||
}
|
||||
|
||||
export const useUserStore = defineStore({
|
||||
id: 'app-user',
|
||||
state: (): UserState => ({
|
||||
// user info
|
||||
userInfo: null,
|
||||
// token
|
||||
token: undefined,
|
||||
// roleList
|
||||
roleList: [],
|
||||
// Whether the login expired
|
||||
sessionTimeout: false,
|
||||
// Last fetch time
|
||||
lastUpdateTime: 0,
|
||||
}),
|
||||
getters: {
|
||||
getUserInfo(): UserInfo {
|
||||
return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
|
||||
},
|
||||
getToken(): string {
|
||||
return this.token || getAuthCache<string>(TOKEN_KEY);
|
||||
},
|
||||
getRoleList(): RoleInfo[] {
|
||||
return this.roleList && this.roleList.length > 0
|
||||
? this.roleList
|
||||
: getAuthCache<RoleInfo[]>(ROLES_KEY);
|
||||
},
|
||||
getSessionTimeout(): boolean {
|
||||
return !!this.sessionTimeout;
|
||||
},
|
||||
getLastUpdateTime(): number {
|
||||
return this.lastUpdateTime;
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
setToken(info: string | undefined) {
|
||||
this.token = info ? info : ''; // for null or undefined value
|
||||
setAuthCache(TOKEN_KEY, info);
|
||||
},
|
||||
setRoleList(roleList: RoleInfo[]) {
|
||||
this.roleList = roleList;
|
||||
setAuthCache(ROLES_KEY, roleList);
|
||||
},
|
||||
setUserInfo(info: UserInfo | null) {
|
||||
this.userInfo = info;
|
||||
this.lastUpdateTime = new Date().getTime();
|
||||
setAuthCache(USER_INFO_KEY, info);
|
||||
},
|
||||
setSessionTimeout(flag: boolean) {
|
||||
this.sessionTimeout = flag;
|
||||
},
|
||||
resetState() {
|
||||
this.userInfo = null;
|
||||
this.token = '';
|
||||
this.roleList = [];
|
||||
this.sessionTimeout = false;
|
||||
},
|
||||
/**
|
||||
* @description: OAUTH Login
|
||||
*/
|
||||
async oauthLogin(
|
||||
params: {
|
||||
token: string;
|
||||
} & {
|
||||
goHome?: boolean;
|
||||
mode?: ErrorMessageMode;
|
||||
},
|
||||
): Promise<GetUserInfoModel | null> {
|
||||
try {
|
||||
const { goHome = true, token } = params;
|
||||
|
||||
// save token
|
||||
this.setToken(token);
|
||||
|
||||
return this.afterLoginAction(goHome);
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @description: login
|
||||
*/
|
||||
async login(
|
||||
params: LoginParams & {
|
||||
goHome?: boolean;
|
||||
mode?: ErrorMessageMode;
|
||||
},
|
||||
): Promise<GetUserInfoModel | null> {
|
||||
try {
|
||||
const { goHome = true, mode, ...loginParams } = params;
|
||||
const data = await loginApi(loginParams, mode);
|
||||
|
||||
const { token } = data;
|
||||
// save token
|
||||
this.setToken(token);
|
||||
|
||||
return this.afterLoginAction(goHome);
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
},
|
||||
async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
|
||||
if (!this.getToken) return null;
|
||||
|
||||
// get user info
|
||||
const userInfo = await this.getUserInfoAction();
|
||||
|
||||
// setOtherToken(this.getToken);
|
||||
|
||||
const sessionTimeout = this.sessionTimeout;
|
||||
if (sessionTimeout) {
|
||||
this.setSessionTimeout(false);
|
||||
} else {
|
||||
const permissionStore = usePermissionStore();
|
||||
|
||||
if (!permissionStore.isDynamicAddedRoute) {
|
||||
const routes = await permissionStore.buildRoutesAction();
|
||||
routes.forEach((route) => {
|
||||
router.addRoute(route as unknown as RouteRecordRaw);
|
||||
});
|
||||
router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
|
||||
permissionStore.setDynamicAddedRoute(true);
|
||||
}
|
||||
goHome && (await router.replace(userInfo?.homePath || PageEnum.BASE_HOME));
|
||||
}
|
||||
|
||||
setOtherToken(this.getToken);
|
||||
return Promise.resolve(userInfo);
|
||||
},
|
||||
async getUserInfoAction(): Promise<GetUserInfoModel | null> {
|
||||
if (!this.getToken) return null;
|
||||
const userInfoResult = await getUserInfo();
|
||||
|
||||
const { roles = [] } = userInfoResult;
|
||||
|
||||
const userInfo = userInfoResult as unknown as UserInfo;
|
||||
this.setUserInfo(userInfo);
|
||||
this.setRoleList(roles);
|
||||
return Promise.resolve(userInfoResult);
|
||||
},
|
||||
/**
|
||||
* @description: logout
|
||||
*/
|
||||
async logout(goLogin = false) {
|
||||
if (this.getToken) {
|
||||
try {
|
||||
await doLogout();
|
||||
} catch {
|
||||
console.log('注销Token失败');
|
||||
}
|
||||
}
|
||||
this.setToken(undefined);
|
||||
this.setSessionTimeout(false);
|
||||
this.setUserInfo(null);
|
||||
goLogin && router.push(PageEnum.BASE_LOGIN);
|
||||
},
|
||||
|
||||
/**
|
||||
* @description: Confirm before logging out
|
||||
*/
|
||||
confirmLoginOut() {
|
||||
const { createConfirm } = useMessage();
|
||||
const { t } = useI18n();
|
||||
createConfirm({
|
||||
iconType: 'warning',
|
||||
title: () => h('span', t('温馨提醒')),
|
||||
content: () => h('span', t('是否确认退出系统?')),
|
||||
onOk: async () => {
|
||||
await this.logout(true);
|
||||
},
|
||||
okText: () => t('确认'),
|
||||
cancelText: () => t('取消'),
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Need to be used outside the setup
|
||||
export function useUserStoreWithOut() {
|
||||
return useUserStore(store);
|
||||
}
|
||||
|
||||
//设置其他url 项目 token
|
||||
function setOtherToken(token: string) {
|
||||
// console.log('other token', getAppEnvConfig()); // something like: "https://codegeex.cn" or "https://codegeex.cn" or
|
||||
getAppEnvConfig()
|
||||
.VITE_GLOB_OUT_LINK_URL?.split(',')
|
||||
?.forEach((item) => {
|
||||
// 创建子域的iframe, 用于传送数据
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.src = `${item}`;
|
||||
iframe.style.display = 'none';
|
||||
document.body.append(iframe);
|
||||
|
||||
// 使用postMessage()发送数据到子系统
|
||||
setTimeout(function () {
|
||||
iframe.contentWindow?.postMessage(token, item);
|
||||
}, 2000);
|
||||
|
||||
// 销毁iframe
|
||||
setTimeout(function () {
|
||||
iframe.remove();
|
||||
}, 4000);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user