init
This commit is contained in:
5
src/store/index.ts
Normal file
5
src/store/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { createPinia } from 'pinia';
|
||||
|
||||
const store = createPinia();
|
||||
|
||||
export default store;
|
||||
73
src/store/modules/app.ts
Normal file
73
src/store/modules/app.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import enUS from 'element-plus/es/locale/lang/en';
|
||||
import zhCN from 'element-plus/es/locale/lang/zh-cn';
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, reactive, ref } from 'vue';
|
||||
|
||||
export const useAppStore = defineStore('app', () => {
|
||||
const sidebarStatus = useStorage('sidebarStatus', '1');
|
||||
const sidebar = reactive({
|
||||
opened: sidebarStatus.value ? !!+sidebarStatus.value : true,
|
||||
withoutAnimation: false,
|
||||
hide: false
|
||||
});
|
||||
const device = ref<string>('desktop');
|
||||
const size = useStorage<'large' | 'default' | 'small'>('size', 'default');
|
||||
|
||||
// 语言
|
||||
const language = useStorage('language', 'zh_CN');
|
||||
const languageObj: any = {
|
||||
en_US: enUS,
|
||||
zh_CN: zhCN
|
||||
};
|
||||
const locale = computed(() => {
|
||||
return languageObj[language.value];
|
||||
});
|
||||
|
||||
const toggleSideBar = (withoutAnimation: boolean) => {
|
||||
if (sidebar.hide) {
|
||||
return false;
|
||||
}
|
||||
|
||||
sidebar.opened = !sidebar.opened;
|
||||
sidebar.withoutAnimation = withoutAnimation;
|
||||
if (sidebar.opened) {
|
||||
sidebarStatus.value = '1';
|
||||
} else {
|
||||
sidebarStatus.value = '0';
|
||||
}
|
||||
};
|
||||
|
||||
const closeSideBar = ({ withoutAnimation }: any): void => {
|
||||
sidebarStatus.value = '0';
|
||||
sidebar.opened = false;
|
||||
sidebar.withoutAnimation = withoutAnimation;
|
||||
};
|
||||
const toggleDevice = (d: string): void => {
|
||||
device.value = d;
|
||||
};
|
||||
const setSize = (s: 'large' | 'default' | 'small'): void => {
|
||||
size.value = s;
|
||||
};
|
||||
const toggleSideBarHide = (status: boolean): void => {
|
||||
sidebar.hide = status;
|
||||
};
|
||||
|
||||
const changeLanguage = (val: string): void => {
|
||||
language.value = val;
|
||||
};
|
||||
|
||||
return {
|
||||
device,
|
||||
sidebar,
|
||||
language,
|
||||
locale,
|
||||
size,
|
||||
changeLanguage,
|
||||
toggleSideBar,
|
||||
closeSideBar,
|
||||
toggleDevice,
|
||||
setSize,
|
||||
toggleSideBarHide
|
||||
};
|
||||
});
|
||||
65
src/store/modules/dict.ts
Normal file
65
src/store/modules/dict.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
export const useDictStore = defineStore('dict', () => {
|
||||
const dict = ref<Map<string, DictDataOption[]>>(new Map());
|
||||
|
||||
/**
|
||||
* 获取字典
|
||||
* @param _key 字典key
|
||||
*/
|
||||
const getDict = (_key: string): DictDataOption[] | null => {
|
||||
if (!_key) {
|
||||
return null;
|
||||
}
|
||||
return dict.value.get(_key) || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置字典
|
||||
* @param _key 字典key
|
||||
* @param _value 字典value
|
||||
*/
|
||||
const setDict = (_key: string, _value: DictDataOption[]) => {
|
||||
if (!_key) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
dict.value.set(_key, _value);
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Error in setDict:', e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除字典
|
||||
* @param _key
|
||||
*/
|
||||
const removeDict = (_key: string): boolean => {
|
||||
if (!_key) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return dict.value.delete(_key);
|
||||
} catch (e) {
|
||||
console.error('Error in removeDict:', e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空字典
|
||||
*/
|
||||
const cleanDict = (): void => {
|
||||
dict.value.clear();
|
||||
};
|
||||
|
||||
return {
|
||||
dict,
|
||||
getDict,
|
||||
setDict,
|
||||
removeDict,
|
||||
cleanDict
|
||||
};
|
||||
});
|
||||
96
src/store/modules/notice.ts
Normal file
96
src/store/modules/notice.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, reactive } from 'vue';
|
||||
|
||||
export interface NoticeItem {
|
||||
messageId?: string | number;
|
||||
title?: string;
|
||||
category?: string;
|
||||
type?: string;
|
||||
source?: string;
|
||||
read: boolean;
|
||||
message: string;
|
||||
content?: string;
|
||||
data?: Record<string, any> | null;
|
||||
path?: string;
|
||||
timestamp?: number;
|
||||
time: string;
|
||||
}
|
||||
|
||||
export const useNoticeStore = defineStore('notice', () => {
|
||||
const state = reactive({
|
||||
notices: [] as NoticeItem[]
|
||||
});
|
||||
|
||||
const unreadCount = computed(() => state.notices.filter(item => !item.read).length);
|
||||
|
||||
const buildNoticeKey = (notice: NoticeItem) => {
|
||||
if (notice.messageId !== undefined && notice.messageId !== null) {
|
||||
return String(notice.messageId);
|
||||
}
|
||||
return [notice.type, notice.source, notice.timestamp, notice.message].join(':');
|
||||
};
|
||||
|
||||
const sortNotices = () => {
|
||||
state.notices.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
||||
};
|
||||
|
||||
const setNotices = (notices: NoticeItem[]) => {
|
||||
state.notices = [...notices];
|
||||
sortNotices();
|
||||
};
|
||||
|
||||
const addNotice = (notice: NoticeItem) => {
|
||||
const key = buildNoticeKey(notice);
|
||||
const index = state.notices.findIndex(item => buildNoticeKey(item) === key);
|
||||
if (index > -1) {
|
||||
state.notices[index] = {
|
||||
...state.notices[index],
|
||||
...notice
|
||||
};
|
||||
} else {
|
||||
state.notices.unshift(notice);
|
||||
}
|
||||
sortNotices();
|
||||
};
|
||||
|
||||
const markRead = (messageId?: string | number) => {
|
||||
if (messageId === undefined || messageId === null) {
|
||||
return;
|
||||
}
|
||||
const target = state.notices.find(item => String(item.messageId) === String(messageId));
|
||||
if (target) {
|
||||
target.read = true;
|
||||
}
|
||||
};
|
||||
|
||||
const markReadBatch = (messageIds: Array<string | number>) => {
|
||||
const idSet = new Set(messageIds.map(item => String(item)));
|
||||
state.notices.forEach(item => {
|
||||
if (item.messageId !== undefined && item.messageId !== null && idSet.has(String(item.messageId))) {
|
||||
item.read = true;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const readAll = () => {
|
||||
markReadBatch(
|
||||
state.notices
|
||||
.map(item => item.messageId)
|
||||
.filter((item): item is string | number => item !== undefined && item !== null)
|
||||
);
|
||||
};
|
||||
|
||||
const clearNotice = () => {
|
||||
state.notices = [];
|
||||
};
|
||||
return {
|
||||
state,
|
||||
unreadCount,
|
||||
setNotices,
|
||||
addNotice,
|
||||
markRead,
|
||||
markReadBatch,
|
||||
readAll,
|
||||
clearNotice
|
||||
};
|
||||
});
|
||||
213
src/store/modules/permission.ts
Normal file
213
src/store/modules/permission.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import { getRouters } from '@/api/menu';
|
||||
import ParentView from '@/components/ParentView/index.vue';
|
||||
import InnerLink from '@/layout/components/InnerLink/index.vue';
|
||||
import Layout from '@/layout/index.vue';
|
||||
import auth from '@/plugins/auth';
|
||||
import router, { constantRoutes, dynamicRoutes } from '@/router';
|
||||
import store from '@/store';
|
||||
import { createCustomNameComponent } from '@/utils/createCustomNameComponent';
|
||||
|
||||
// 匹配views里面所有的.vue文件,预建查找表避免每次 O(n) 扫描
|
||||
const modules = import.meta.glob('./../../views/**/*.vue');
|
||||
const viewModuleMap = new Map<string, () => Promise<any>>();
|
||||
for (const path in modules) {
|
||||
const viewsIndex = path.indexOf('/views/');
|
||||
if (viewsIndex === -1) continue;
|
||||
const dir = path.substring(viewsIndex + 7, path.lastIndexOf('.vue'));
|
||||
viewModuleMap.set(dir, modules[path] as () => Promise<any>);
|
||||
}
|
||||
export const usePermissionStore = defineStore('permission', () => {
|
||||
const routes = ref<RouteRecordRaw[]>([]);
|
||||
const addRoutes = ref<RouteRecordRaw[]>([]);
|
||||
const defaultRoutes = ref<RouteRecordRaw[]>([]);
|
||||
const topbarRouters = ref<RouteRecordRaw[]>([]);
|
||||
const sidebarRouters = ref<RouteRecordRaw[]>([]);
|
||||
|
||||
const getRoutes = (): RouteRecordRaw[] => {
|
||||
return routes.value as RouteRecordRaw[];
|
||||
};
|
||||
const getDefaultRoutes = (): RouteRecordRaw[] => {
|
||||
return defaultRoutes.value as RouteRecordRaw[];
|
||||
};
|
||||
const getSidebarRoutes = (): RouteRecordRaw[] => {
|
||||
return sidebarRouters.value as RouteRecordRaw[];
|
||||
};
|
||||
const getTopbarRoutes = (): RouteRecordRaw[] => {
|
||||
return topbarRouters.value as RouteRecordRaw[];
|
||||
};
|
||||
|
||||
const setRoutes = (newRoutes: RouteRecordRaw[]): void => {
|
||||
addRoutes.value = newRoutes;
|
||||
routes.value = constantRoutes.concat(newRoutes);
|
||||
};
|
||||
const setDefaultRoutes = (routes: RouteRecordRaw[]): void => {
|
||||
defaultRoutes.value = constantRoutes.concat(routes);
|
||||
};
|
||||
const setTopbarRoutes = (routes: RouteRecordRaw[]): void => {
|
||||
topbarRouters.value = routes;
|
||||
};
|
||||
const setSidebarRouters = (routes: RouteRecordRaw[]): void => {
|
||||
sidebarRouters.value = routes;
|
||||
};
|
||||
const generateRoutes = async (): Promise<RouteRecordRaw[]> => {
|
||||
const res = await getRouters();
|
||||
const data = Array.isArray(res.data) ? res.data : [];
|
||||
const sdata = structuredClone(data);
|
||||
const rdata = structuredClone(data);
|
||||
const defaultData = structuredClone(data);
|
||||
const sidebarRoutes = filterAsyncRouter(sdata);
|
||||
const rewriteRoutes = filterAsyncRouter(rdata, undefined, true);
|
||||
const defaultRoutes = filterAsyncRouter(defaultData);
|
||||
const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
|
||||
asyncRoutes.forEach(route => {
|
||||
router.addRoute(route);
|
||||
});
|
||||
setRoutes(rewriteRoutes);
|
||||
setSidebarRouters(constantRoutes.concat(sidebarRoutes));
|
||||
setDefaultRoutes(sidebarRoutes);
|
||||
setTopbarRoutes(defaultRoutes);
|
||||
// 路由name重复检查
|
||||
duplicateRouteChecker(asyncRoutes, sidebarRoutes);
|
||||
return rewriteRoutes;
|
||||
};
|
||||
|
||||
/**
|
||||
* 遍历后台传来的路由字符串,转换为组件对象
|
||||
* @param asyncRouterMap 后台传来的路由字符串
|
||||
* @param lastRouter 上一级路由
|
||||
* @param type 是否是重写路由
|
||||
*/
|
||||
const filterAsyncRouter = (
|
||||
asyncRouterMap: RouteRecordRaw[],
|
||||
lastRouter?: RouteRecordRaw,
|
||||
type = false
|
||||
): RouteRecordRaw[] => {
|
||||
return asyncRouterMap.filter(route => {
|
||||
if (type && route.children) {
|
||||
route.children = filterChildren(route.children, undefined);
|
||||
}
|
||||
// Layout ParentView 组件特殊处理
|
||||
if (route.component?.toString() === 'Layout') {
|
||||
route.component = Layout;
|
||||
} else if (route.component?.toString() === 'ParentView') {
|
||||
route.component = ParentView;
|
||||
} else if (route.component?.toString() === 'InnerLink') {
|
||||
route.component = InnerLink;
|
||||
} else {
|
||||
route.component = loadView(route.component, route.name as string);
|
||||
}
|
||||
if (route.children != null && route.children && route.children.length) {
|
||||
route.children = filterAsyncRouter(route.children, route, type);
|
||||
} else {
|
||||
delete route.children;
|
||||
delete route.redirect;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
const filterChildren = (childrenMap: RouteRecordRaw[], lastRouter?: RouteRecordRaw): RouteRecordRaw[] => {
|
||||
let children: RouteRecordRaw[] = [];
|
||||
childrenMap.forEach(el => {
|
||||
el.path = lastRouter ? lastRouter.path + '/' + el.path : el.path;
|
||||
if (el.children && el.children.length && el.component?.toString() === 'ParentView') {
|
||||
children = children.concat(filterChildren(el.children, el));
|
||||
} else {
|
||||
children.push(el);
|
||||
}
|
||||
});
|
||||
return children;
|
||||
};
|
||||
return {
|
||||
routes,
|
||||
topbarRouters,
|
||||
sidebarRouters,
|
||||
defaultRoutes,
|
||||
|
||||
getRoutes,
|
||||
getDefaultRoutes,
|
||||
getSidebarRoutes,
|
||||
getTopbarRoutes,
|
||||
|
||||
setRoutes,
|
||||
generateRoutes,
|
||||
setSidebarRouters
|
||||
};
|
||||
});
|
||||
|
||||
// 动态路由遍历,验证是否具备权限
|
||||
export const filterDynamicRoutes = (routes: RouteRecordRaw[]) => {
|
||||
const res: RouteRecordRaw[] = [];
|
||||
routes.forEach(route => {
|
||||
if (route.permissions) {
|
||||
if (auth.hasPermiOr(route.permissions)) {
|
||||
res.push(route);
|
||||
}
|
||||
} else if (route.roles) {
|
||||
if (auth.hasRoleOr(route.roles)) {
|
||||
res.push(route);
|
||||
}
|
||||
}
|
||||
});
|
||||
return res;
|
||||
};
|
||||
|
||||
export const loadView = (view: any, name: string) => {
|
||||
const loader = viewModuleMap.get(view);
|
||||
if (loader) {
|
||||
return createCustomNameComponent(loader, { name });
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
// 非setup
|
||||
export const usePermissionStoreHook = () => {
|
||||
return usePermissionStore(store);
|
||||
};
|
||||
|
||||
interface Route {
|
||||
name?: string | symbol;
|
||||
path: string;
|
||||
children?: Route[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路由name是否重复
|
||||
* @param localRoutes 本地路由
|
||||
* @param routes 动态路由
|
||||
*/
|
||||
function duplicateRouteChecker(localRoutes: Route[], routes: Route[]) {
|
||||
// 展平
|
||||
function flatRoutes(routes: Route[]) {
|
||||
const res: Route[] = [];
|
||||
routes.forEach(route => {
|
||||
if (route.children) {
|
||||
res.push(...flatRoutes(route.children));
|
||||
} else {
|
||||
res.push(route);
|
||||
}
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
const allRoutes = flatRoutes([...localRoutes, ...routes]);
|
||||
|
||||
const nameList: string[] = [];
|
||||
allRoutes.forEach(route => {
|
||||
const name = route.name?.toString() ?? '';
|
||||
if (!name) return;
|
||||
if (nameList.includes(name)) {
|
||||
const message = `路由名称: [${name}] 重复, 会造成 404`;
|
||||
console.error(message);
|
||||
ElNotification({
|
||||
title: '路由名称重复',
|
||||
message,
|
||||
type: 'error'
|
||||
});
|
||||
return;
|
||||
}
|
||||
nameList.push(name);
|
||||
});
|
||||
}
|
||||
60
src/store/modules/settings.ts
Normal file
60
src/store/modules/settings.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import { NavTypeEnum } from '@/enums/NavTypeEnum';
|
||||
import defaultSettings from '@/settings';
|
||||
import { useDynamicTitle } from '@/utils/dynamicTitle';
|
||||
|
||||
export const useSettingsStore = defineStore('setting', () => {
|
||||
const storageSetting = useStorage<LayoutSetting>('layout-setting', {
|
||||
tagsView: defaultSettings.tagsView,
|
||||
tagsViewPersist: defaultSettings.tagsViewPersist,
|
||||
tagsIcon: defaultSettings.tagsIcon,
|
||||
fixedHeader: defaultSettings.fixedHeader,
|
||||
sidebarLogo: defaultSettings.sidebarLogo,
|
||||
dynamicTitle: defaultSettings.dynamicTitle,
|
||||
sideTheme: defaultSettings.sideTheme,
|
||||
theme: defaultSettings.theme,
|
||||
navType: defaultSettings.navType,
|
||||
radiusBase: defaultSettings.radiusBase,
|
||||
fullHeightTable: defaultSettings.fullHeightTable
|
||||
});
|
||||
const title = ref<string>(defaultSettings.title);
|
||||
const theme = ref<string>(storageSetting.value.theme);
|
||||
const sideTheme = ref<string>(storageSetting.value.sideTheme);
|
||||
const showSettings = ref<boolean>(defaultSettings.showSettings);
|
||||
const tagsView = ref<boolean>(storageSetting.value.tagsView);
|
||||
const tagsViewPersist = ref<boolean>(storageSetting.value.tagsViewPersist);
|
||||
const tagsIcon = ref<boolean>(storageSetting.value.tagsIcon);
|
||||
const fixedHeader = ref<boolean>(storageSetting.value.fixedHeader);
|
||||
const sidebarLogo = ref<boolean>(storageSetting.value.sidebarLogo);
|
||||
const dynamicTitle = ref<boolean>(storageSetting.value.dynamicTitle);
|
||||
const animationEnable = ref<boolean>(defaultSettings.animationEnable);
|
||||
const dark = ref<boolean>(defaultSettings.dark);
|
||||
const navType = ref<NavTypeEnum>(storageSetting.value.navType || NavTypeEnum.LEFT);
|
||||
const radiusBase = ref<number>(storageSetting.value.radiusBase ?? defaultSettings.radiusBase);
|
||||
const fullHeightTable = ref<boolean>(storageSetting.value.fullHeightTable ?? defaultSettings.fullHeightTable);
|
||||
|
||||
const setTitle = (value: string) => {
|
||||
title.value = value;
|
||||
useDynamicTitle();
|
||||
};
|
||||
return {
|
||||
title,
|
||||
theme,
|
||||
sideTheme,
|
||||
showSettings,
|
||||
tagsView,
|
||||
tagsViewPersist,
|
||||
tagsIcon,
|
||||
fixedHeader,
|
||||
sidebarLogo,
|
||||
dynamicTitle,
|
||||
animationEnable,
|
||||
dark,
|
||||
navType,
|
||||
radiusBase,
|
||||
fullHeightTable,
|
||||
setTitle
|
||||
};
|
||||
});
|
||||
337
src/store/modules/tagsView.ts
Normal file
337
src/store/modules/tagsView.ts
Normal file
@@ -0,0 +1,337 @@
|
||||
import type { LocationQuery, RouteLocationNormalized, RouteMeta } from 'vue-router';
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import { useSettingsStore } from './settings';
|
||||
|
||||
const PERSIST_KEY = 'tags-view-visited';
|
||||
|
||||
type PersistedTagView = {
|
||||
path: string;
|
||||
fullPath?: string;
|
||||
name?: string | symbol | null;
|
||||
title?: string;
|
||||
query?: LocationQuery;
|
||||
meta?: RouteMeta;
|
||||
};
|
||||
|
||||
type TagView = RouteLocationNormalized & {
|
||||
title?: string;
|
||||
};
|
||||
|
||||
const isPersistEnabled = () => {
|
||||
return useSettingsStore().tagsViewPersist;
|
||||
};
|
||||
|
||||
const normalizeVisitedView = (view: RouteLocationNormalized): TagView => {
|
||||
return Object.assign({}, view, {
|
||||
title: view.meta?.title || 'no-name'
|
||||
});
|
||||
};
|
||||
|
||||
const saveVisitedViews = (views: any[]) => {
|
||||
if (!isPersistEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: PersistedTagView[] = (views as TagView[])
|
||||
.filter(view => !view.meta?.affix)
|
||||
.map(view => ({
|
||||
path: view.path,
|
||||
fullPath: view.fullPath,
|
||||
name: view.name,
|
||||
title: (view as any).title || view.meta?.title || 'no-name',
|
||||
query: view.query,
|
||||
meta: view.meta
|
||||
}));
|
||||
|
||||
localStorage.setItem(PERSIST_KEY, JSON.stringify(payload));
|
||||
};
|
||||
|
||||
const loadVisitedViews = (): PersistedTagView[] => {
|
||||
const cache = localStorage.getItem(PERSIST_KEY);
|
||||
if (!cache) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(cache) as PersistedTagView[];
|
||||
} catch {
|
||||
localStorage.removeItem(PERSIST_KEY);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const clearVisitedViews = () => {
|
||||
localStorage.removeItem(PERSIST_KEY);
|
||||
};
|
||||
|
||||
export const useTagsViewStore = defineStore('tagsView', () => {
|
||||
const visitedViews = ref<TagView[]>([]);
|
||||
const cachedViews = ref<string[]>([]);
|
||||
const iframeViews = ref<TagView[]>([]);
|
||||
|
||||
const getVisitedViews = (): TagView[] => {
|
||||
return visitedViews.value as TagView[];
|
||||
};
|
||||
const getIframeViews = (): TagView[] => {
|
||||
return iframeViews.value as TagView[];
|
||||
};
|
||||
const getCachedViews = (): string[] => {
|
||||
return cachedViews.value;
|
||||
};
|
||||
|
||||
const addView = (view: RouteLocationNormalized) => {
|
||||
addVisitedView(view);
|
||||
addCachedView(view);
|
||||
};
|
||||
|
||||
const addIframeView = (view: RouteLocationNormalized): void => {
|
||||
if (iframeViews.value.some((v: RouteLocationNormalized) => v.path === view.path)) return;
|
||||
iframeViews.value.push(normalizeVisitedView(view) as RouteLocationNormalized);
|
||||
};
|
||||
|
||||
const delIframeView = (view: RouteLocationNormalized): Promise<RouteLocationNormalized[]> => {
|
||||
return new Promise(resolve => {
|
||||
iframeViews.value = iframeViews.value.filter((item: RouteLocationNormalized) => item.path !== view.path);
|
||||
resolve(iframeViews.value.slice() as RouteLocationNormalized[]);
|
||||
});
|
||||
};
|
||||
|
||||
const addVisitedView = (view: RouteLocationNormalized): void => {
|
||||
if (visitedViews.value.some((v: RouteLocationNormalized) => v.path === view.path)) return;
|
||||
visitedViews.value.push(normalizeVisitedView(view));
|
||||
saveVisitedViews(visitedViews.value);
|
||||
};
|
||||
|
||||
const addAffixView = (view: RouteLocationNormalized): void => {
|
||||
if (visitedViews.value.some((v: RouteLocationNormalized) => v.path === view.path)) return;
|
||||
const insertIndex = visitedViews.value.findIndex(item => !item.meta?.affix);
|
||||
const normalizedView = normalizeVisitedView(view);
|
||||
if (insertIndex === -1) {
|
||||
visitedViews.value.push(normalizedView);
|
||||
} else {
|
||||
visitedViews.value.splice(insertIndex, 0, normalizedView);
|
||||
}
|
||||
};
|
||||
|
||||
const loadPersistedViews = (): void => {
|
||||
loadVisitedViews().forEach(view => {
|
||||
if (visitedViews.value.some(item => item.path === view.path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
visitedViews.value.push({
|
||||
hash: '',
|
||||
matched: [],
|
||||
params: {},
|
||||
redirectedFrom: undefined,
|
||||
path: view.path,
|
||||
fullPath: view.fullPath || view.path,
|
||||
query: view.query || {},
|
||||
name: view.name || undefined,
|
||||
meta: view.meta || {},
|
||||
title: view.title || view.meta?.title || 'no-name'
|
||||
} as TagView);
|
||||
});
|
||||
};
|
||||
|
||||
const delView = (
|
||||
view: RouteLocationNormalized
|
||||
): Promise<{
|
||||
visitedViews: RouteLocationNormalized[];
|
||||
cachedViews: string[];
|
||||
}> => {
|
||||
return new Promise(resolve => {
|
||||
delVisitedView(view);
|
||||
delCachedView(view);
|
||||
resolve({
|
||||
visitedViews: visitedViews.value.slice() as RouteLocationNormalized[],
|
||||
cachedViews: [...cachedViews.value]
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const delVisitedView = (view: RouteLocationNormalized): Promise<RouteLocationNormalized[]> => {
|
||||
return new Promise(resolve => {
|
||||
for (const [i, v] of visitedViews.value.entries()) {
|
||||
if (v.path === view.path) {
|
||||
visitedViews.value.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
saveVisitedViews(visitedViews.value);
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
});
|
||||
};
|
||||
|
||||
const delCachedView = (view?: RouteLocationNormalized): Promise<string[]> => {
|
||||
let viewName = '';
|
||||
if (view) {
|
||||
viewName = view.name as string;
|
||||
}
|
||||
return new Promise(resolve => {
|
||||
const index = cachedViews.value.indexOf(viewName);
|
||||
index > -1 && cachedViews.value.splice(index, 1);
|
||||
resolve([...cachedViews.value]);
|
||||
});
|
||||
};
|
||||
|
||||
const delOthersViews = (
|
||||
view: RouteLocationNormalized
|
||||
): Promise<{
|
||||
visitedViews: RouteLocationNormalized[];
|
||||
cachedViews: string[];
|
||||
}> => {
|
||||
return new Promise(resolve => {
|
||||
delOthersVisitedViews(view);
|
||||
delOthersCachedViews(view);
|
||||
resolve({
|
||||
visitedViews: visitedViews.value.slice() as RouteLocationNormalized[],
|
||||
cachedViews: [...cachedViews.value]
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const delOthersVisitedViews = (view: RouteLocationNormalized): Promise<RouteLocationNormalized[]> => {
|
||||
return new Promise(resolve => {
|
||||
visitedViews.value = visitedViews.value.filter((v: RouteLocationNormalized) => {
|
||||
return v.meta?.affix || v.path === view.path;
|
||||
});
|
||||
saveVisitedViews(visitedViews.value);
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
});
|
||||
};
|
||||
|
||||
const delOthersCachedViews = (view: RouteLocationNormalized): Promise<string[]> => {
|
||||
const viewName = view.name as string;
|
||||
return new Promise(resolve => {
|
||||
const index = cachedViews.value.indexOf(viewName);
|
||||
if (index > -1) {
|
||||
cachedViews.value = cachedViews.value.slice(index, index + 1);
|
||||
} else {
|
||||
cachedViews.value = [];
|
||||
}
|
||||
resolve([...cachedViews.value]);
|
||||
});
|
||||
};
|
||||
|
||||
const delAllViews = (): Promise<{
|
||||
visitedViews: RouteLocationNormalized[];
|
||||
cachedViews: string[];
|
||||
}> => {
|
||||
return new Promise(resolve => {
|
||||
delAllVisitedViews();
|
||||
delAllCachedViews();
|
||||
resolve({
|
||||
visitedViews: visitedViews.value.slice() as RouteLocationNormalized[],
|
||||
cachedViews: [...cachedViews.value]
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const delAllVisitedViews = (): Promise<RouteLocationNormalized[]> => {
|
||||
return new Promise(resolve => {
|
||||
visitedViews.value = visitedViews.value.filter((tag: RouteLocationNormalized) => tag.meta?.affix);
|
||||
clearVisitedViews();
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
});
|
||||
};
|
||||
|
||||
const delAllCachedViews = (): Promise<string[]> => {
|
||||
return new Promise(resolve => {
|
||||
cachedViews.value = [];
|
||||
resolve([...cachedViews.value]);
|
||||
});
|
||||
};
|
||||
|
||||
const updateVisitedView = (view: RouteLocationNormalized): void => {
|
||||
for (let v of visitedViews.value) {
|
||||
if (v.path === view.path) {
|
||||
v = Object.assign(v, view);
|
||||
break;
|
||||
}
|
||||
}
|
||||
saveVisitedViews(visitedViews.value);
|
||||
};
|
||||
|
||||
const delRightTags = (view: RouteLocationNormalized): Promise<RouteLocationNormalized[]> => {
|
||||
return new Promise(resolve => {
|
||||
const index = visitedViews.value.findIndex((v: RouteLocationNormalized) => v.path === view.path);
|
||||
if (index === -1) {
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
return;
|
||||
}
|
||||
visitedViews.value = visitedViews.value.filter((item: RouteLocationNormalized, idx: number) => {
|
||||
if (idx <= index || (item.meta && item.meta.affix)) {
|
||||
return true;
|
||||
}
|
||||
const i = cachedViews.value.indexOf(item.name as string);
|
||||
if (i > -1) {
|
||||
cachedViews.value.splice(i, 1);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
saveVisitedViews(visitedViews.value);
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
});
|
||||
};
|
||||
|
||||
const delLeftTags = (view: RouteLocationNormalized): Promise<RouteLocationNormalized[]> => {
|
||||
return new Promise(resolve => {
|
||||
const index = visitedViews.value.findIndex((v: RouteLocationNormalized) => v.path === view.path);
|
||||
if (index === -1) {
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
return;
|
||||
}
|
||||
visitedViews.value = visitedViews.value.filter((item: RouteLocationNormalized, idx: number) => {
|
||||
if (idx >= index || (item.meta && item.meta.affix)) {
|
||||
return true;
|
||||
}
|
||||
const i = cachedViews.value.indexOf(item.name as string);
|
||||
if (i > -1) {
|
||||
cachedViews.value.splice(i, 1);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
saveVisitedViews(visitedViews.value);
|
||||
resolve(visitedViews.value.slice() as RouteLocationNormalized[]);
|
||||
});
|
||||
};
|
||||
|
||||
const addCachedView = (view: RouteLocationNormalized): void => {
|
||||
const viewName = view.name as string;
|
||||
if (!viewName) return;
|
||||
if (cachedViews.value.includes(viewName)) return;
|
||||
if (!view.meta?.noCache) {
|
||||
cachedViews.value.push(viewName);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
visitedViews,
|
||||
cachedViews,
|
||||
iframeViews,
|
||||
|
||||
getVisitedViews,
|
||||
getIframeViews,
|
||||
getCachedViews,
|
||||
|
||||
addVisitedView,
|
||||
addAffixView,
|
||||
addCachedView,
|
||||
delVisitedView,
|
||||
delCachedView,
|
||||
updateVisitedView,
|
||||
addView,
|
||||
delView,
|
||||
delAllViews,
|
||||
delAllVisitedViews,
|
||||
delAllCachedViews,
|
||||
delOthersViews,
|
||||
delRightTags,
|
||||
delLeftTags,
|
||||
addIframeView,
|
||||
delIframeView,
|
||||
loadPersistedViews
|
||||
};
|
||||
});
|
||||
91
src/store/modules/user.ts
Normal file
91
src/store/modules/user.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { to } from 'await-to-js';
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import type { UserInfo } from '@/api/system/user/types';
|
||||
import type { LoginData, LoginResult } from '@/api/types';
|
||||
import type { RuoYiAjaxResult } from '@/utils/api-types';
|
||||
import { getInfo as getUserInfo, login as loginApi, logout as logoutApi } from '@/api/login';
|
||||
import defAva from '@/assets/images/profile.jpg';
|
||||
import { getToken, removeToken, setToken } from '@/utils/auth';
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const token = ref(getToken());
|
||||
const name = ref('');
|
||||
const nickname = ref('');
|
||||
const userId = ref<string | number>('');
|
||||
const avatar = ref('');
|
||||
const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
|
||||
const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
|
||||
|
||||
/**
|
||||
* 登录
|
||||
* @param userInfo
|
||||
* @returns
|
||||
*/
|
||||
const login = async (userInfo: LoginData): Promise<void> => {
|
||||
const [err, res] = await to(loginApi(userInfo));
|
||||
if (res) {
|
||||
const data = (res as RuoYiAjaxResult<LoginResult>).data;
|
||||
if (!data?.access_token) {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
setToken(data.access_token);
|
||||
token.value = data.access_token;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return Promise.reject(err);
|
||||
};
|
||||
|
||||
// 获取用户信息
|
||||
const getInfo = async (): Promise<void> => {
|
||||
const [err, res] = await to(getUserInfo());
|
||||
if (res) {
|
||||
const data = (res as RuoYiAjaxResult<UserInfo>).data;
|
||||
if (!data?.user) {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
const user = data.user;
|
||||
const profile = user.avatarUrl == '' || user.avatarUrl == null ? defAva : user.avatarUrl;
|
||||
|
||||
if (data.roles && data.roles.length > 0) {
|
||||
// 验证返回的roles是否是一个非空数组
|
||||
roles.value = data.roles;
|
||||
permissions.value = data.permissions;
|
||||
} else {
|
||||
roles.value = ['ROLE_DEFAULT'];
|
||||
}
|
||||
name.value = user.userName;
|
||||
nickname.value = user.nickName;
|
||||
avatar.value = profile;
|
||||
userId.value = user.userId;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return Promise.reject(err);
|
||||
};
|
||||
|
||||
// 注销
|
||||
const logout = async (): Promise<void> => {
|
||||
await logoutApi();
|
||||
token.value = '';
|
||||
roles.value = [];
|
||||
permissions.value = [];
|
||||
removeToken();
|
||||
};
|
||||
|
||||
const setAvatar = (value: string) => {
|
||||
avatar.value = value;
|
||||
};
|
||||
|
||||
return {
|
||||
userId,
|
||||
token,
|
||||
nickname,
|
||||
avatar,
|
||||
roles,
|
||||
permissions,
|
||||
login,
|
||||
getInfo,
|
||||
logout,
|
||||
setAvatar
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user