refactor: Separate store

This commit is contained in:
vben
2024-07-30 21:10:28 +08:00
parent cf0ec053e4
commit 89dcf522f5
40 changed files with 338 additions and 345 deletions

View File

@@ -33,6 +33,6 @@ const authDirective: Directive = {
mounted,
};
export function useAccessDirective(app: App) {
export function registerAccessDirective(app: App) {
app.directive('access', authDirective);
}

View File

@@ -1,10 +1,11 @@
import { computed } from 'vue';
import { preferences, updatePreferences } from '@vben/preferences';
import { useCoreAccessStore } from '@vben/stores';
import { useAccessStore, useUserStore } from '@vben/stores';
function useAccess() {
const coreAccessStore = useCoreAccessStore();
const accessStore = useAccessStore();
const userStore = useUserStore();
const accessMode = computed(() => {
return preferences.app.accessMode;
});
@@ -15,7 +16,7 @@ function useAccess() {
* @param roles
*/
function hasAccessByRoles(roles: string[]) {
const userRoleSet = new Set(coreAccessStore.userRoles);
const userRoleSet = new Set(userStore.userRoles);
const intersection = roles.filter((item) => userRoleSet.has(item));
return intersection.length > 0;
}
@@ -26,7 +27,7 @@ function useAccess() {
* @param codes
*/
function hasAccessByCodes(codes: string[]) {
const userCodesSet = new Set(coreAccessStore.accessCodes);
const userCodesSet = new Set(accessStore.accessCodes);
const intersection = codes.filter((item) => userCodesSet.has(item));
return intersection.length > 0;

View File

@@ -1,13 +1,13 @@
import { useRouter } from 'vue-router';
import { useCoreTabbarStore } from '@vben/stores';
import { useTabbarStore } from '@vben/stores';
export function useRefresh() {
const router = useRouter();
const coreTabbarStore = useCoreTabbarStore();
const tabbarStore = useTabbarStore();
function refresh() {
coreTabbarStore.refresh(router);
tabbarStore.refresh(router);
}
return {

View File

@@ -1,64 +1,64 @@
import { type RouteLocationNormalized, useRoute, useRouter } from 'vue-router';
import { useCoreTabbarStore } from '@vben/stores';
import { useTabbarStore } from '@vben/stores';
export function useTabs() {
const router = useRouter();
const route = useRoute();
const coreTabbarStore = useCoreTabbarStore();
const tabbarStore = useTabbarStore();
async function closeLeftTabs(tab?: RouteLocationNormalized) {
await coreTabbarStore.closeLeftTabs(tab || route);
await tabbarStore.closeLeftTabs(tab || route);
}
async function closeAllTabs() {
await coreTabbarStore.closeAllTabs(router);
await tabbarStore.closeAllTabs(router);
}
async function closeRightTabs(tab?: RouteLocationNormalized) {
await coreTabbarStore.closeRightTabs(tab || route);
await tabbarStore.closeRightTabs(tab || route);
}
async function closeOtherTabs(tab?: RouteLocationNormalized) {
await coreTabbarStore.closeOtherTabs(tab || route);
await tabbarStore.closeOtherTabs(tab || route);
}
async function closeCurrentTab(tab?: RouteLocationNormalized) {
await coreTabbarStore.closeTab(tab || route, router);
await tabbarStore.closeTab(tab || route, router);
}
async function pinTab(tab?: RouteLocationNormalized) {
await coreTabbarStore.pinTab(tab || route);
await tabbarStore.pinTab(tab || route);
}
async function unpinTab(tab?: RouteLocationNormalized) {
await coreTabbarStore.unpinTab(tab || route);
await tabbarStore.unpinTab(tab || route);
}
async function toggleTabPin(tab?: RouteLocationNormalized) {
await coreTabbarStore.toggleTabPin(tab || route);
await tabbarStore.toggleTabPin(tab || route);
}
async function refreshTab() {
await coreTabbarStore.refresh(router);
await tabbarStore.refresh(router);
}
async function openTabInNewWindow(tab?: RouteLocationNormalized) {
coreTabbarStore.openTabInNewWindow(tab || route);
tabbarStore.openTabInNewWindow(tab || route);
}
async function closeTabByKey(key: string) {
await coreTabbarStore.closeTabByKey(key, router);
await tabbarStore.closeTabByKey(key, router);
}
async function setTabTitle(title: string) {
coreTabbarStore.setUpdateTime();
await coreTabbarStore.setTabTitle(route, title);
tabbarStore.setUpdateTime();
await tabbarStore.setTabTitle(route, title);
}
async function resetTabTitle() {
coreTabbarStore.setUpdateTime();
await coreTabbarStore.resetTabTitle(route);
tabbarStore.setUpdateTime();
await tabbarStore.resetTabTitle(route);
}
/**
@@ -66,8 +66,8 @@ export function useTabs() {
* @param tab
*/
function getTabDisableState(tab: RouteLocationNormalized = route) {
const tabs = coreTabbarStore.getTabs;
const affixTabs = coreTabbarStore.affixTabs;
const tabs = tabbarStore.getTabs;
const affixTabs = tabbarStore.affixTabs;
const index = tabs.findIndex((item) => item.path === tab.path);
const disabled = tabs.length <= 1;

View File

@@ -9,7 +9,7 @@ import { RouterView } from 'vue-router';
import { useContentHeight } from '@vben/hooks';
import { preferences, usePreferences } from '@vben/preferences';
import { storeToRefs, useCoreTabbarStore } from '@vben/stores';
import { storeToRefs, useTabbarStore } from '@vben/stores';
import { Spinner } from '@vben-core/shadcn-ui';
import { IFrameRouterView } from '../../iframe';
@@ -17,7 +17,7 @@ import { useContentSpinner } from './use-content-spinner';
defineOptions({ name: 'LayoutContent' });
const tabbarStore = useCoreTabbarStore();
const tabbarStore = useTabbarStore();
const { keepAlive } = usePreferences();
const { spinning } = useContentSpinner();
const { contentStyles } = useContentHeight();

View File

@@ -1,6 +1,6 @@
<script lang="ts" setup>
import { preferences, usePreferences } from '@vben/preferences';
import { useCoreAccessStore } from '@vben/stores';
import { useAccessStore } from '@vben/stores';
import { VbenFullScreen } from '@vben-core/shadcn-ui';
import { GlobalSearch, LanguageToggle, ThemeToggle } from '../../widgets';
@@ -20,7 +20,7 @@ withDefaults(defineProps<Props>(), {
theme: 'light',
});
const accessStore = useCoreAccessStore();
const accessStore = useAccessStore();
const { globalSearchShortcutKey } = usePreferences();
</script>

View File

@@ -8,7 +8,7 @@ import {
updatePreferences,
usePreferences,
} from '@vben/preferences';
import { useCoreAccessStore, useCoreLockStore } from '@vben/stores';
import { useLockStore, useUserStore } from '@vben/stores';
import { MenuRecordRaw } from '@vben/types';
import { mapTree } from '@vben/utils';
import { VbenAdminLayout } from '@vben-core/layout-ui';
@@ -41,9 +41,9 @@ const {
layout,
sidebarCollapsed,
} = usePreferences();
const coreAccessStore = useCoreAccessStore();
const userStore = useUserStore();
const { updateWatermark } = useWatermark();
const coreLockStore = useCoreLockStore();
const lockStore = useLockStore();
const headerMenuTheme = computed(() => {
return isDark.value ? 'dark' : 'light';
@@ -138,7 +138,7 @@ watch(
// await nextTick();
updateWatermark({
content: `${preferences.app.name} 用户名: ${coreAccessStore.userInfo?.username}`,
content: `${preferences.app.name} 用户名: ${userStore.userInfo?.username}`,
// parent: contentRef.value,
});
}
@@ -317,7 +317,7 @@ watch(
/>
<Transition v-if="preferences.widget.lockScreen" name="slide-up">
<slot v-if="coreLockStore.isLockScreen" name="lock-screen"></slot>
<slot v-if="lockStore.isLockScreen" name="lock-screen"></slot>
</Transition>
</template>
</VbenAdminLayout>

View File

@@ -4,13 +4,13 @@ import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { preferences } from '@vben/preferences';
import { useCoreAccessStore } from '@vben/stores';
import { useAccessStore } from '@vben/stores';
import { findRootMenuByPath } from '@vben/utils';
import { useNavigation } from './use-navigation';
function useExtraMenu() {
const accessStore = useCoreAccessStore();
const accessStore = useAccessStore();
const { navigation } = useNavigation();
const menus = computed(() => accessStore.accessMenus);

View File

@@ -4,14 +4,14 @@ import { computed, onBeforeMount, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { preferences, usePreferences } from '@vben/preferences';
import { useCoreAccessStore } from '@vben/stores';
import { useAccessStore } from '@vben/stores';
import { findRootMenuByPath } from '@vben/utils';
import { useNavigation } from './use-navigation';
function useMixedMenu() {
const { navigation } = useNavigation();
const accessStore = useCoreAccessStore();
const accessStore = useAccessStore();
const route = useRoute();
const splitSideMenus = ref<MenuRecordRaw[]>([]);
const rootMenuPath = ref<string>('');

View File

@@ -4,7 +4,7 @@ import { useRoute } from 'vue-router';
import { useContentMaximize, useTabs } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import { useCoreTabbarStore } from '@vben/stores';
import { useTabbarStore } from '@vben/stores';
import {
TabsToolMore,
TabsToolRefresh,
@@ -21,7 +21,7 @@ defineOptions({
defineProps<{ showIcon?: boolean; theme?: string }>();
const route = useRoute();
const coreTabbarStore = useCoreTabbarStore();
const tabbarStore = useTabbarStore();
const { toggleMaximize } = useContentMaximize();
const { refreshTab, unpinTab } = useTabs();
@@ -34,7 +34,7 @@ const {
} = useTabbar();
const menus = computed(() => {
const tab = coreTabbarStore.getTabByPath(currentActive.value);
const tab = tabbarStore.getTabByPath(currentActive.value);
const menus = createContextMenus(tab);
return menus.map((item) => {
return {
@@ -47,7 +47,7 @@ const menus = computed(() => {
// 刷新后如果不保持tab状态关闭其他tab
if (!preferences.tabbar.persist) {
coreTabbarStore.closeOtherTabs(route);
tabbarStore.closeOtherTabs(route);
}
</script>
@@ -61,7 +61,7 @@ if (!preferences.tabbar.persist) {
:style-type="preferences.tabbar.styleType"
:tabs="currentTabs"
@close="handleClose"
@sort-tabs="coreTabbarStore.sortTabs"
@sort-tabs="tabbarStore.sortTabs"
@unpin="unpinTab"
@update:active="handleClick"
/>

View File

@@ -23,19 +23,14 @@ import {
X,
} from '@vben/icons';
import { $t, useI18n } from '@vben/locales';
import {
storeToRefs,
useCoreAccessStore,
useCoreTabbarStore,
} from '@vben/stores';
import { useAccessStore, useTabbarStore } from '@vben/stores';
import { filterTree } from '@vben/utils';
export function useTabbar() {
const router = useRouter();
const route = useRoute();
const accessStore = useCoreAccessStore();
const coreTabbarStore = useCoreTabbarStore();
const { accessMenus } = storeToRefs(accessStore);
const accessStore = useAccessStore();
const tabbarStore = useTabbarStore();
const { contentIsMaximize, toggleMaximize } = useContentMaximize();
const {
closeAllTabs,
@@ -58,8 +53,8 @@ export function useTabbar() {
const currentTabs = ref<RouteLocationNormalizedGeneric[]>();
watch(
[
() => coreTabbarStore.getTabs,
() => coreTabbarStore.updateTime,
() => tabbarStore.getTabs,
() => tabbarStore.updateTime,
() => locale.value,
],
([tabs]) => {
@@ -74,7 +69,7 @@ export function useTabbar() {
const affixTabs = filterTree(router.getRoutes(), (route) => {
return !!route.meta?.affixTab;
});
coreTabbarStore.setAffixTabs(affixTabs);
tabbarStore.setAffixTabs(affixTabs);
};
// 点击tab,跳转路由
@@ -98,7 +93,7 @@ export function useTabbar() {
}
watch(
() => accessMenus.value,
() => accessStore.accessMenus,
() => {
initAffixTabs();
},
@@ -108,7 +103,7 @@ export function useTabbar() {
watch(
() => route.path,
() => {
coreTabbarStore.addTab(route as RouteLocationNormalized);
tabbarStore.addTab(route as RouteLocationNormalized);
},
{ immediate: true },
);

View File

@@ -5,13 +5,13 @@ import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { preferences } from '@vben/preferences';
import { useCoreTabbarStore } from '@vben/stores';
import { useTabbarStore } from '@vben/stores';
import { Spinner } from '@vben-core/shadcn-ui';
defineOptions({ name: 'IFrameRouterView' });
const spinningList = ref<boolean[]>([]);
const coreTabbarStore = useCoreTabbarStore();
const tabbarStore = useTabbarStore();
const route = useRoute();
const enableTabbar = computed(() => preferences.tabbar.enable);
@@ -20,7 +20,7 @@ const iframeRoutes = computed(() => {
if (!enableTabbar.value) {
return route.meta.iframeSrc ? [route] : [];
}
return coreTabbarStore.getTabs.filter((tab) => !!tab.meta?.iframeSrc);
return tabbarStore.getTabs.filter((tab) => !!tab.meta?.iframeSrc);
});
const tabNames = computed(
@@ -36,7 +36,7 @@ function routeShow(tabItem: RouteLocationNormalized) {
function canRender(tabItem: RouteLocationNormalized) {
const { meta, name } = tabItem;
if (!name || !coreTabbarStore.renderRouteView) {
if (!name || !tabbarStore.renderRouteView) {
return false;
}
@@ -52,7 +52,7 @@ function canRender(tabItem: RouteLocationNormalized) {
) {
return false;
}
return coreTabbarStore.getTabs.some((tab) => tab.name === name);
return tabbarStore.getTabs.some((tab) => tab.name === name);
}
function hideLoading(index: number) {

View File

@@ -3,7 +3,7 @@ import { computed, reactive, ref, watchEffect } from 'vue';
import { LockKeyhole } from '@vben/icons';
import { $t, useI18n } from '@vben/locales';
import { storeToRefs, useCoreLockStore } from '@vben/stores';
import { storeToRefs, useLockStore } from '@vben/stores';
import {
VbenAvatar,
VbenButton,
@@ -27,7 +27,7 @@ withDefaults(defineProps<Props>(), {
defineEmits<{ toLogin: [] }>();
const { locale } = useI18n();
const coreLockStore = useCoreLockStore();
const lockStore = useLockStore();
const now = useNow();
const meridiem = useDateFormat(now, 'A');
@@ -37,7 +37,7 @@ const date = useDateFormat(now, 'YYYY-MM-DD dddd', { locales: locale.value });
const showUnlockForm = ref(false);
const validPass = ref(true);
const { lockScreenPassword } = storeToRefs(coreLockStore);
const { lockScreenPassword } = storeToRefs(lockStore);
const formState = reactive({
password: '',
@@ -77,7 +77,7 @@ function handleSubmit() {
validPass.value = false;
return;
}
coreLockStore.unlockScreen();
lockStore.unlockScreen();
}
function toggleUnlockForm() {

View File

@@ -7,7 +7,7 @@ import { computed, ref } from 'vue';
import { LockKeyhole, LogOut, SwatchBook } from '@vben/icons';
import { $t } from '@vben/locales';
import { preferences, usePreferences } from '@vben/preferences';
import { useCoreLockStore } from '@vben/stores';
import { useLockStore } from '@vben/stores';
import { isWindowsOs } from '@vben/utils';
import {
Badge,
@@ -80,7 +80,7 @@ const {
globalLogoutShortcutKey,
globalPreferencesShortcutKey,
} = usePreferences();
const coreLockStore = useCoreLockStore();
const lockStore = useLockStore();
const { handleOpenPreference } = useOpenPreferences();
const altView = computed(() => (isWindowsOs() ? 'Alt' : '⌥'));
@@ -111,7 +111,7 @@ function handleSubmitLock({
lockScreenPassword: string;
}) {
openLock.value = false;
coreLockStore.lockScreen(lockScreenPassword);
lockStore.lockScreen(lockScreenPassword);
}
function handleLogout() {
// emit

View File

@@ -1,15 +1,15 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useCoreAccessStore } from './access';
import { useAccessStore } from './access';
describe('useCoreAccessStore', () => {
describe('useAccessStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('updates accessMenus state', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
expect(store.accessMenus).toEqual([]);
store.setAccessMenus([{ name: 'Dashboard', path: '/dashboard' }]);
expect(store.accessMenus).toEqual([
@@ -17,68 +17,29 @@ describe('useCoreAccessStore', () => {
]);
});
it('updates userInfo and userRoles state', () => {
const store = useCoreAccessStore();
expect(store.userInfo).toBeNull();
expect(store.userRoles).toEqual([]);
const userInfo: any = { name: 'John Doe', roles: ['admin'] };
store.setUserInfo(userInfo);
expect(store.userInfo).toEqual(userInfo);
expect(store.userRoles).toEqual(['admin']);
});
it('returns correct userInfo', () => {
const store = useCoreAccessStore();
const userInfo: any = { name: 'Jane Doe', roles: [{ value: 'user' }] };
store.setUserInfo(userInfo);
expect(store.userInfo).toEqual(userInfo);
});
it('updates accessToken state correctly', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
expect(store.accessToken).toBeNull(); // 初始状态
store.setAccessToken('abc123');
expect(store.accessToken).toBe('abc123');
});
// 测试重置用户信息时的行为
it('clears userInfo and userRoles when setting null userInfo', () => {
const store = useCoreAccessStore();
store.setUserInfo({
roles: [{ roleName: 'User', value: 'user' }],
} as any);
expect(store.userInfo).not.toBeNull();
expect(store.userRoles.length).toBeGreaterThan(0);
store.setUserInfo(null as any); // 重置用户信息
expect(store.userInfo).toBeNull();
expect(store.userRoles).toEqual([]);
});
it('returns the correct accessToken', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
store.setAccessToken('xyz789');
expect(store.accessToken).toBe('xyz789');
});
// 测试在没有用户角色时返回空数组
it('returns an empty array for userRoles if not set', () => {
const store = useCoreAccessStore();
expect(store.userRoles).toEqual([]);
});
// 测试设置空的访问菜单列表
it('handles empty accessMenus correctly', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
store.setAccessMenus([]);
expect(store.accessMenus).toEqual([]);
});
// 测试设置空的访问路由列表
it('handles empty accessRoutes correctly', () => {
const store = useCoreAccessStore();
const store = useAccessStore();
store.setAccessRoutes([]);
expect(store.accessRoutes).toEqual([]);
});

View File

@@ -5,29 +5,6 @@ import { acceptHMRUpdate, defineStore } from 'pinia';
type AccessToken = null | string;
interface BasicUserInfo {
/**
* 头像
*/
avatar: string;
/**
* 用户昵称
*/
realName: string;
/**
* 用户角色
*/
roles?: string[];
/**
* 用户id
*/
userId: string;
/**
* 用户名
*/
username: string;
}
interface AccessState {
/**
* 权限码
@@ -45,24 +22,20 @@ interface AccessState {
* 登录 accessToken
*/
accessToken: AccessToken;
/**
* 登录是否过期
*/
loginExpired: boolean;
/**
* 登录 accessToken
*/
refreshToken: AccessToken;
/**
* 用户信息
*/
userInfo: BasicUserInfo | null;
/**
* 用户角色
*/
userRoles: string[];
}
/**
* @zh_CN 访问权限相关
*/
export const useCoreAccessStore = defineStore('core-access', {
export const useAccessStore = defineStore('core-access', {
actions: {
setAccessCodes(codes: string[]) {
this.accessCodes = codes;
@@ -76,19 +49,12 @@ export const useCoreAccessStore = defineStore('core-access', {
setAccessToken(token: AccessToken) {
this.accessToken = token;
},
setLoginExpired(loginExpired: boolean) {
this.loginExpired = loginExpired;
},
setRefreshToken(token: AccessToken) {
this.refreshToken = token;
},
setUserInfo(userInfo: BasicUserInfo | null) {
// 设置用户信息
this.userInfo = userInfo;
// 设置角色信息
const roles = userInfo?.roles ?? [];
this.setUserRoles(roles);
},
setUserRoles(roles: string[]) {
this.userRoles = roles;
},
},
persist: {
// 持久化
@@ -99,14 +65,13 @@ export const useCoreAccessStore = defineStore('core-access', {
accessMenus: [],
accessRoutes: [],
accessToken: null,
loginExpired: false,
refreshToken: null,
userInfo: null,
userRoles: [],
}),
});
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useCoreAccessStore, hot));
hot.accept(acceptHMRUpdate(useAccessStore, hot));
}

View File

@@ -1,3 +1,4 @@
export * from './access';
export * from './lock';
export * from './tabbar';
export * from './user';

View File

@@ -1,29 +1,29 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useCoreLockStore } from './lock';
import { useLockStore } from './lock';
describe('useCoreLockStore', () => {
describe('useLockStore', () => {
beforeEach(() => {
// 每个测试前重置 Pinia
setActivePinia(createPinia());
});
it('should initialize with correct default state', () => {
const store = useCoreLockStore();
const store = useLockStore();
expect(store.isLockScreen).toBe(false);
expect(store.lockScreenPassword).toBeUndefined();
});
it('should lock screen with a password', () => {
const store = useCoreLockStore();
const store = useLockStore();
store.lockScreen('1234');
expect(store.isLockScreen).toBe(true);
expect(store.lockScreenPassword).toBe('1234');
});
it('should unlock screen and clear password', () => {
const store = useCoreLockStore();
const store = useLockStore();
store.lockScreen('1234');
store.unlockScreen();
expect(store.isLockScreen).toBe(false);

View File

@@ -11,7 +11,7 @@ interface AppState {
lockScreenPassword?: string;
}
export const useCoreLockStore = defineStore('core-lock', {
export const useLockStore = defineStore('core-lock', {
actions: {
lockScreen(password: string) {
this.isLockScreen = true;

View File

@@ -3,9 +3,9 @@ import { createRouter, createWebHistory } from 'vue-router';
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useCoreTabbarStore } from './tabbar';
import { useTabbarStore } from './tabbar';
describe('useCoreAccessStore', () => {
describe('useAccessStore', () => {
const router = createRouter({
history: createWebHistory(),
routes: [],
@@ -18,7 +18,7 @@ describe('useCoreAccessStore', () => {
});
it('adds a new tab', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const tab: any = {
fullPath: '/home',
meta: {},
@@ -31,7 +31,7 @@ describe('useCoreAccessStore', () => {
});
it('adds a new tab if it does not exist', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const newTab: any = {
fullPath: '/new',
meta: {},
@@ -43,7 +43,7 @@ describe('useCoreAccessStore', () => {
});
it('updates an existing tab instead of adding a new one', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const initialTab: any = {
fullPath: '/existing',
meta: {},
@@ -59,7 +59,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.tabs = [
{ fullPath: '/home', meta: {}, name: 'Home', path: '/home' },
] as any;
@@ -72,7 +72,7 @@ describe('useCoreAccessStore', () => {
});
it('closes a non-affix tab', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const tab: any = {
fullPath: '/closable',
meta: {},
@@ -85,7 +85,7 @@ describe('useCoreAccessStore', () => {
});
it('does not close an affix tab', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const affixTab: any = {
fullPath: '/affix',
meta: { affixTab: true },
@@ -98,14 +98,14 @@ describe('useCoreAccessStore', () => {
});
it('returns all cache tabs', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.cachedTabs.add('Home');
store.cachedTabs.add('About');
expect(store.getCachedTabs).toEqual(['Home', 'About']);
});
it('returns all tabs, including affix tabs', () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const normalTab: any = {
fullPath: '/normal',
meta: {},
@@ -125,7 +125,7 @@ describe('useCoreAccessStore', () => {
});
it('navigates to a specific tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const tab: any = { meta: {}, name: 'Dashboard', path: '/dashboard' };
await store._goToTab(tab, router);
@@ -138,7 +138,7 @@ describe('useCoreAccessStore', () => {
});
it('closes multiple tabs by paths', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@@ -165,7 +165,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs to the left of the specified tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@@ -193,7 +193,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs except the specified tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@@ -221,7 +221,7 @@ describe('useCoreAccessStore', () => {
});
it('closes all tabs to the right of the specified tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const targetTab: any = {
fullPath: '/home',
meta: {},
@@ -249,7 +249,7 @@ describe('useCoreAccessStore', () => {
});
it('closes the tab with the specified key', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const keyToClose = '/about';
store.addTab({
fullPath: '/home',
@@ -279,7 +279,7 @@ describe('useCoreAccessStore', () => {
});
it('refreshes the current tab', async () => {
const store = useCoreTabbarStore();
const store = useTabbarStore();
const currentTab: any = {
fullPath: '/dashboard',
meta: { name: 'Dashboard' },

View File

@@ -7,7 +7,7 @@ import { openWindow, startProgress, stopProgress } from '@vben-core/shared';
import { acceptHMRUpdate, defineStore } from 'pinia';
interface TabsState {
interface TabbarState {
/**
* @zh_CN 当前打开的标签页列表缓存
*/
@@ -37,7 +37,7 @@ interface TabsState {
/**
* @zh_CN 访问权限相关
*/
export const useCoreTabbarStore = defineStore('core-tabbar', {
export const useTabbarStore = defineStore('core-tabbar', {
actions: {
/**
* Close tabs in bulk
@@ -441,7 +441,7 @@ export const useCoreTabbarStore = defineStore('core-tabbar', {
storage: sessionStorage,
},
],
state: (): TabsState => ({
state: (): TabbarState => ({
cachedTabs: new Set(),
dragEndIndex: 0,
excludeCachedTabs: new Set(),
@@ -454,7 +454,7 @@ export const useCoreTabbarStore = defineStore('core-tabbar', {
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useCoreTabbarStore, hot));
hot.accept(acceptHMRUpdate(useTabbarStore, hot));
}
/**

View File

@@ -0,0 +1,37 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useUserStore } from './user';
describe('useUserStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('returns correct userInfo', () => {
const store = useUserStore();
const userInfo: any = { name: 'Jane Doe', roles: [{ value: 'user' }] };
store.setUserInfo(userInfo);
expect(store.userInfo).toEqual(userInfo);
});
// 测试重置用户信息时的行为
it('clears userInfo and userRoles when setting null userInfo', () => {
const store = useUserStore();
store.setUserInfo({
roles: [{ roleName: 'User', value: 'user' }],
} as any);
expect(store.userInfo).not.toBeNull();
expect(store.userRoles.length).toBeGreaterThan(0);
store.setUserInfo(null as any); // 重置用户信息
expect(store.userInfo).toBeNull();
expect(store.userRoles).toEqual([]);
});
// 测试在没有用户角色时返回空数组
it('returns an empty array for userRoles if not set', () => {
const store = useUserStore();
expect(store.userRoles).toEqual([]);
});
});

View File

@@ -0,0 +1,63 @@
import { acceptHMRUpdate, defineStore } from 'pinia';
interface BasicUserInfo {
/**
* 头像
*/
avatar: string;
/**
* 用户昵称
*/
realName: string;
/**
* 用户角色
*/
roles?: string[];
/**
* 用户id
*/
userId: string;
/**
* 用户名
*/
username: string;
}
interface AccessState {
/**
* 用户信息
*/
userInfo: BasicUserInfo | null;
/**
* 用户角色
*/
userRoles: string[];
}
/**
* @zh_CN 用户信息相关
*/
export const useUserStore = defineStore('core-user', {
actions: {
setUserInfo(userInfo: BasicUserInfo | null) {
// 设置用户信息
this.userInfo = userInfo;
// 设置角色信息
const roles = userInfo?.roles ?? [];
this.setUserRoles(roles);
},
setUserRoles(roles: string[]) {
this.userRoles = roles;
},
},
state: (): AccessState => ({
userInfo: null,
userRoles: [],
}),
});
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useUserStore, hot));
}

View File

@@ -1,5 +1,7 @@
import type { Pinia } from 'pinia';
import type { App } from 'vue';
import { createPinia } from 'pinia';
let pinia: Pinia;
@@ -14,7 +16,7 @@ export interface InitStoreOptions {
/**
* @zh_CN 初始化pinia
*/
export async function initStore(options: InitStoreOptions) {
export async function initStores(app: App, options: InitStoreOptions) {
const { createPersistedState } = await import('pinia-plugin-persistedstate');
pinia = createPinia();
const { namespace } = options;
@@ -25,6 +27,7 @@ export async function initStore(options: InitStoreOptions) {
storage: localStorage,
}),
);
app.use(pinia);
return pinia;
}

View File

@@ -3,4 +3,5 @@ export * from './generate-menus';
export * from './generate-routes-backend';
export * from './generate-routes-frontend';
export * from './merge-route-modules';
export * from './reset-routes';
export * from './unmount-global-loading';

View File

@@ -0,0 +1,31 @@
import type { Router, RouteRecordName, RouteRecordRaw } from 'vue-router';
import { traverseTreeValues } from '@vben-core/shared/utils';
/**
* @zh_CN 重置所有路由,如有指定白名单除外
*/
export function resetStaticRoutes(router: Router, routes: RouteRecordRaw[]) {
// 获取静态路由所有节点包含子节点的 name并排除不存在 name 字段的路由
const staticRouteNames = traverseTreeValues<
RouteRecordRaw,
RouteRecordName | undefined
>(routes, (route) => {
// 这些路由需要指定 name防止在路由重置时不能删除没有指定 name 的路由
if (!route.name) {
console.warn(
`The route with the path ${route.path} needs to have the field name specified.`,
);
}
return route.name;
});
const { getRoutes, hasRoute, removeRoute } = router;
const allRoutes = getRoutes();
allRoutes.forEach(({ name }) => {
// 存在于路由表且非白名单才需要删除
if (name && !staticRouteNames.includes(name) && hasRoute(name)) {
removeRoute(name);
}
});
}