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

@ -6,10 +6,11 @@ import type { HttpResponse } from '@vben/request';
import { useAppConfig } from '@vben/hooks'; import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences'; import { preferences } from '@vben/preferences';
import { RequestClient } from '@vben/request'; import { RequestClient } from '@vben/request';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue'; import { message } from 'ant-design-vue';
import { useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
@ -30,13 +31,14 @@ function createRequestClient(baseURL: string) {
}, },
unAuthorizedHandler: async () => { unAuthorizedHandler: async () => {
const accessStore = useAccessStore(); const accessStore = useAccessStore();
const authStore = useAuthStore();
accessStore.setAccessToken(null); accessStore.setAccessToken(null);
if (preferences.app.loginExpiredMode === 'modal') { if (preferences.app.loginExpiredMode === 'modal') {
accessStore.openLoginExpiredModal = true; accessStore.setLoginExpired(true);
} else { } else {
// 退出登录 // 退出登录
await accessStore.logout(); await authStore.logout();
} }
}, },
}; };

View File

@ -1,11 +1,11 @@
import { createApp } from 'vue'; import { createApp } from 'vue';
import { useAccessDirective } from '@vben/access'; import { registerAccessDirective } from '@vben/access';
import { initStores } from '@vben/stores';
import '@vben/styles'; import '@vben/styles';
import '@vben/styles/antd'; import '@vben/styles/antd';
import { setupI18n } from '#/locales'; import { setupI18n } from '#/locales';
import { setupStore } from '#/store';
import App from './app.vue'; import App from './app.vue';
import { router } from './router'; import { router } from './router';
@ -17,10 +17,10 @@ async function bootstrap(namespace: string) {
await setupI18n(app); await setupI18n(app);
// 配置 pinia-tore // 配置 pinia-tore
await setupStore(app, { namespace }); await initStores(app, { namespace });
// 安装权限指令 // 安装权限指令
useAccessDirective(app); registerAccessDirective(app);
// 配置路由及路由守卫 // 配置路由及路由守卫
app.use(router); app.use(router);

View File

@ -13,11 +13,17 @@ import {
UserDropdown, UserDropdown,
} from '@vben/layouts'; } from '@vben/layouts';
import { preferences } from '@vben/preferences'; import { preferences } from '@vben/preferences';
import {
resetAllStores,
storeToRefs,
useAccessStore,
useUserStore,
} from '@vben/stores';
import { openWindow } from '@vben/utils'; import { openWindow } from '@vben/utils';
import { $t } from '#/locales'; import { $t } from '#/locales';
import { resetRoutes } from '#/router'; import { resetRoutes } from '#/router';
import { resetAllStores, storeToRefs, useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
const notifications = ref<NotificationItem[]>([ const notifications = ref<NotificationItem[]>([
{ {
@ -50,6 +56,9 @@ const notifications = ref<NotificationItem[]>([
}, },
]); ]);
const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const showDot = computed(() => const showDot = computed(() =>
notifications.value.some((item) => !item.isRead), notifications.value.some((item) => !item.isRead),
); );
@ -84,16 +93,10 @@ const menus = computed(() => [
}, },
]); ]);
const accessStore = useAccessStore(); const { loginLoading } = storeToRefs(authStore);
const {
loading: loginLoading,
openLoginExpiredModal,
userInfo,
} = storeToRefs(accessStore);
const avatar = computed(() => { const avatar = computed(() => {
return userInfo.value?.avatar ?? preferences.app.defaultAvatar; return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
}); });
const router = useRouter(); const router = useRouter();
@ -119,7 +122,7 @@ function handleMakeAll() {
<UserDropdown <UserDropdown
:avatar :avatar
:menus :menus
:text="userInfo?.realName" :text="userStore.userInfo?.realName"
description="ann.vben@gmail.com" description="ann.vben@gmail.com"
tag-text="Pro" tag-text="Pro"
@logout="handleLogout" @logout="handleLogout"
@ -135,12 +138,12 @@ function handleMakeAll() {
</template> </template>
<template #extra> <template #extra>
<AuthenticationLoginExpiredModal <AuthenticationLoginExpiredModal
v-model:open="openLoginExpiredModal" v-model:open="accessStore.loginExpired"
:avatar :avatar
:loading="loginLoading" :loading="loginLoading"
password-placeholder="123456" password-placeholder="123456"
username-placeholder="vben" username-placeholder="vben"
@submit="accessStore.authLogin" @submit="authStore.authLogin"
/> />
</template> </template>
<template #lock-screen> <template #lock-screen>

View File

@ -2,13 +2,14 @@ import type { Router } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants'; import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences'; import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { startProgress, stopProgress } from '@vben/utils'; import { startProgress, stopProgress } from '@vben/utils';
import { useTitle } from '@vueuse/core'; import { useTitle } from '@vueuse/core';
import { $t } from '#/locales'; import { $t } from '#/locales';
import { coreRouteNames, dynamicRoutes } from '#/router/routes'; import { coreRouteNames, dynamicRoutes } from '#/router/routes';
import { useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
import { generateAccess } from './access'; import { generateAccess } from './access';
@ -58,10 +59,11 @@ function setupCommonGuard(router: Router) {
function setupAccessGuard(router: Router) { function setupAccessGuard(router: Router) {
router.beforeEach(async (to, from) => { router.beforeEach(async (to, from) => {
const accessStore = useAccessStore(); const accessStore = useAccessStore();
const accessToken = accessStore.accessToken; const userStore = useUserStore();
const authStore = useAuthStore();
// accessToken 检查 // accessToken 检查
if (!accessToken) { if (!accessStore.accessToken) {
if ( if (
// 基本路由,这些路由不需要进入权限拦截 // 基本路由,这些路由不需要进入权限拦截
coreRouteNames.includes(to.name as string) || coreRouteNames.includes(to.name as string) ||
@ -93,8 +95,7 @@ function setupAccessGuard(router: Router) {
// 生成路由表 // 生成路由表
// 当前登录用户拥有的角色标识列表 // 当前登录用户拥有的角色标识列表
const userInfo = const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());
accessStore.userInfo || (await accessStore.fetchUserInfo());
const userRoles = userInfo.roles ?? []; const userRoles = userInfo.roles ?? [];
// 生成菜单和路由 // 生成菜单和路由

View File

@ -1,12 +1,10 @@
import type { RouteRecordName, RouteRecordRaw } from 'vue-router';
import { import {
createRouter, createRouter,
createWebHashHistory, createWebHashHistory,
createWebHistory, createWebHistory,
} from 'vue-router'; } from 'vue-router';
import { traverseTreeValues } from '@vben/utils'; import { resetStaticRoutes } from '@vben/utils';
import { createRouterGuard } from './guard'; import { createRouterGuard } from './guard';
import { routes } from './routes'; import { routes } from './routes';
@ -26,33 +24,8 @@ const router = createRouter({
// strict: true, // strict: true,
}); });
/** const resetRoutes = () => resetStaticRoutes(router, routes);
* @zh_CN
*/
function resetRoutes() {
// 获取静态路由所有节点包含子节点的 name并排除不存在 name 字段的路由
const staticRouteNames = traverseTreeValues<
RouteRecordRaw,
RouteRecordName | undefined
>(routes, (route) => {
// 这些路由需要指定 name防止在路由重置时不能删除没有指定 name 的路由
if (import.meta.env.DEV && !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);
}
});
}
// 创建路由守卫 // 创建路由守卫
createRouterGuard(router); createRouterGuard(router);

View File

@ -1,12 +1,11 @@
import type { LoginAndRegisterParams } from '@vben/common-ui'; import type { LoginAndRegisterParams } from '@vben/common-ui';
import type { MenuRecordRaw, UserInfo } from '@vben/types'; import type { UserInfo } from '@vben/types';
import type { RouteRecordRaw } from 'vue-router';
import { computed, ref } from 'vue'; import { ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useCoreAccessStore } from '@vben/stores'; import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { notification } from 'ant-design-vue'; import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
@ -14,31 +13,12 @@ import { defineStore } from 'pinia';
import { getAccessCodes, getUserInfo, login } from '#/api'; import { getAccessCodes, getUserInfo, login } from '#/api';
import { $t } from '#/locales'; import { $t } from '#/locales';
export const useAccessStore = defineStore('access', () => { export const useAuthStore = defineStore('auth', () => {
const coreStoreAccess = useCoreAccessStore(); const accessStore = useAccessStore();
const userStore = useUserStore();
const router = useRouter(); const router = useRouter();
const loading = ref(false); const loginLoading = ref(false);
const openLoginExpiredModal = ref(false);
const accessToken = computed(() => coreStoreAccess.accessToken);
const refreshToken = computed(() => coreStoreAccess.refreshToken);
const userRoles = computed(() => coreStoreAccess.userRoles);
const userInfo = computed(() => coreStoreAccess.userInfo);
const accessRoutes = computed(() => coreStoreAccess.accessRoutes);
function setAccessMenus(menus: MenuRecordRaw[]) {
coreStoreAccess.setAccessMenus(menus);
}
function setAccessToken(token: null | string) {
coreStoreAccess.setAccessToken(token);
}
function setAccessRoutes(routes: RouteRecordRaw[]) {
coreStoreAccess.setAccessRoutes(routes);
}
/** /**
* *
@ -52,19 +32,16 @@ export const useAccessStore = defineStore('access', () => {
// 异步处理用户登录操作并获取 accessToken // 异步处理用户登录操作并获取 accessToken
let userInfo: null | UserInfo = null; let userInfo: null | UserInfo = null;
try { try {
loading.value = true; loginLoading.value = true;
const { accessToken, refreshToken } = await login(params); const { accessToken, refreshToken } = await login(params);
// 如果成功获取到 accessToken // 如果成功获取到 accessToken
// If accessToken is successfully obtained
if (accessToken) { if (accessToken) {
// 将 accessToken 存储到 accessStore 中 // 将 accessToken 存储到 accessStore 中
// Store the accessToken in accessStore accessStore.setAccessToken(accessToken);
coreStoreAccess.setAccessToken(accessToken); accessStore.setRefreshToken(refreshToken);
coreStoreAccess.setRefreshToken(refreshToken);
// 获取用户信息并存储到 accessStore 中 // 获取用户信息并存储到 accessStore 中
// Get user information and store it in accessStore
const [fetchUserInfoResult, accessCodes] = await Promise.all([ const [fetchUserInfoResult, accessCodes] = await Promise.all([
fetchUserInfo(), fetchUserInfo(),
getAccessCodes(), getAccessCodes(),
@ -72,11 +49,11 @@ export const useAccessStore = defineStore('access', () => {
userInfo = fetchUserInfoResult; userInfo = fetchUserInfoResult;
coreStoreAccess.setUserInfo(userInfo); userStore.setUserInfo(userInfo);
coreStoreAccess.setAccessCodes(accessCodes); accessStore.setAccessCodes(accessCodes);
if (openLoginExpiredModal.value) { if (accessStore.loginExpired) {
openLoginExpiredModal.value = false; accessStore.setLoginExpired(false);
} else { } else {
onSuccess onSuccess
? await onSuccess?.() ? await onSuccess?.()
@ -92,18 +69,17 @@ export const useAccessStore = defineStore('access', () => {
} }
} }
} finally { } finally {
loading.value = false; loginLoading.value = false;
} }
return { return {
accessToken,
userInfo, userInfo,
}; };
} }
async function logout() { async function logout() {
resetAllStores(); resetAllStores();
openLoginExpiredModal.value = false; accessStore.setLoginExpired(false);
// 回登陆页带上当前路由地址 // 回登陆页带上当前路由地址
await router.replace({ await router.replace({
@ -117,29 +93,19 @@ export const useAccessStore = defineStore('access', () => {
async function fetchUserInfo() { async function fetchUserInfo() {
let userInfo: null | UserInfo = null; let userInfo: null | UserInfo = null;
userInfo = await getUserInfo(); userInfo = await getUserInfo();
coreStoreAccess.setUserInfo(userInfo); userStore.setUserInfo(userInfo);
return userInfo; return userInfo;
} }
function $reset() { function $reset() {
loading.value = false; loginLoading.value = false;
openLoginExpiredModal.value = false;
} }
return { return {
$reset, $reset,
accessRoutes,
accessToken,
authLogin, authLogin,
fetchUserInfo, fetchUserInfo,
loading, loginLoading,
logout, logout,
openLoginExpiredModal,
refreshToken,
setAccessMenus,
setAccessRoutes,
setAccessToken,
userInfo,
userRoles,
}; };
}); });

View File

@ -1,18 +1 @@
import type { InitStoreOptions } from '@vben/stores'; export * from './auth';
import type { App } from 'vue';
import { initStore, resetAllStores, storeToRefs } from '@vben/stores';
/**
* @zh_CN pinia
* @param app vue app
*/
async function setupStore(app: App, options: InitStoreOptions) {
const pinia = await initStore(options);
app.use(pinia);
}
export { resetAllStores, setupStore, storeToRefs };
export { useAccessStore } from './modules/access';

View File

@ -1,18 +1,18 @@
<script lang="ts" setup> <script lang="ts" setup>
import { AuthenticationLogin } from '@vben/common-ui'; import { AuthenticationLogin } from '@vben/common-ui';
import { useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
defineOptions({ name: 'Login' }); defineOptions({ name: 'Login' });
const accessStore = useAccessStore(); const authStore = useAuthStore();
</script> </script>
<template> <template>
<AuthenticationLogin <AuthenticationLogin
:loading="accessStore.loading" :loading="authStore.loginLoading"
password-placeholder="123456" password-placeholder="123456"
username-placeholder="vben" username-placeholder="vben"
@submit="accessStore.authLogin" @submit="authStore.authLogin"
/> />
</template> </template>

View File

@ -17,12 +17,11 @@ import {
WorkbenchTrends, WorkbenchTrends,
} from '@vben/common-ui'; } from '@vben/common-ui';
import { preferences } from '@vben/preferences'; import { preferences } from '@vben/preferences';
import { useUserStore } from '@vben/stores';
import { useAccessStore } from '#/store';
import AnalyticsVisitsSource from '../analytics/analytics-visits-source.vue'; import AnalyticsVisitsSource from '../analytics/analytics-visits-source.vue';
const accessStore = useAccessStore(); const userStore = useUserStore();
const projectItems: WorkbenchProjectItem[] = [ const projectItems: WorkbenchProjectItem[] = [
{ {
@ -201,10 +200,10 @@ const trendItems: WorkbenchTrendItem[] = [
<template> <template>
<div class="p-5"> <div class="p-5">
<WorkbenchHeader <WorkbenchHeader
:avatar="accessStore.userInfo?.avatar || preferences.app.defaultAvatar" :avatar="userStore.userInfo?.avatar || preferences.app.defaultAvatar"
> >
<template #title> <template #title>
早安, {{ accessStore.userInfo?.realName }}, 开始您一天的工作吧 早安, {{ userStore.userInfo?.realName }}, 开始您一天的工作吧
</template> </template>
<template #description> 今日晴20 - 32 </template> <template #description> 今日晴20 - 32 </template>
</WorkbenchHeader> </WorkbenchHeader>

View File

@ -4,10 +4,11 @@ import type { LoginAndRegisterParams } from '@vben/common-ui';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { AccessControl, useAccess } from '@vben/access'; import { AccessControl, useAccess } from '@vben/access';
import { resetAllStores, useUserStore } from '@vben/stores';
import { Button } from 'ant-design-vue'; import { Button } from 'ant-design-vue';
import { resetAllStores, useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
const accounts: Record<string, LoginAndRegisterParams> = { const accounts: Record<string, LoginAndRegisterParams> = {
admin: { admin: {
@ -25,21 +26,22 @@ const accounts: Record<string, LoginAndRegisterParams> = {
}; };
const { accessMode, hasAccessByCodes } = useAccess(); const { accessMode, hasAccessByCodes } = useAccess();
const accessStore = useAccessStore(); const authStore = useAuthStore();
const userStore = useUserStore();
const router = useRouter(); const router = useRouter();
function roleButtonType(role: string) { function roleButtonType(role: string) {
return accessStore.userRoles.includes(role) ? 'primary' : 'default'; return userStore.userRoles.includes(role) ? 'primary' : 'default';
} }
async function changeAccount(role: string) { async function changeAccount(role: string) {
if (accessStore.userRoles.includes(role)) { if (userStore.userRoles.includes(role)) {
return; return;
} }
const account = accounts[role]; const account = accounts[role];
resetAllStores(); resetAllStores();
await accessStore.authLogin(account, async () => { await authStore.authLogin(account, async () => {
router.go(0); router.go(0);
}); });
} }
@ -58,7 +60,7 @@ async function changeAccount(role: string) {
<div class="mb-3"> <div class="mb-3">
<span class="text-lg font-semibold">当前角色:</span> <span class="text-lg font-semibold">当前角色:</span>
<span class="text-primary mx-4 text-lg"> <span class="text-primary mx-4 text-lg">
{{ accessStore.userRoles?.[0] }} {{ userStore.userRoles?.[0] }}
</span> </span>
</div> </div>

View File

@ -4,10 +4,11 @@ import type { LoginAndRegisterParams } from '@vben/common-ui';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useAccess } from '@vben/access'; import { useAccess } from '@vben/access';
import { resetAllStores, useUserStore } from '@vben/stores';
import { Button } from 'ant-design-vue'; import { Button } from 'ant-design-vue';
import { resetAllStores, useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
const accounts: Record<string, LoginAndRegisterParams> = { const accounts: Record<string, LoginAndRegisterParams> = {
admin: { admin: {
@ -25,15 +26,16 @@ const accounts: Record<string, LoginAndRegisterParams> = {
}; };
const { accessMode, toggleAccessMode } = useAccess(); const { accessMode, toggleAccessMode } = useAccess();
const accessStore = useAccessStore(); const userStore = useUserStore();
const accessStore = useAuthStore();
const router = useRouter(); const router = useRouter();
function roleButtonType(role: string) { function roleButtonType(role: string) {
return accessStore.userRoles.includes(role) ? 'primary' : 'default'; return userStore.userRoles.includes(role) ? 'primary' : 'default';
} }
async function changeAccount(role: string) { async function changeAccount(role: string) {
if (accessStore.userRoles.includes(role)) { if (userStore.userRoles.includes(role)) {
return; return;
} }
@ -80,7 +82,7 @@ async function handleToggleAccessMode() {
<div class="mb-3"> <div class="mb-3">
<span class="text-lg font-semibold">当前账号:</span> <span class="text-lg font-semibold">当前账号:</span>
<span class="text-primary mx-4 text-lg"> <span class="text-primary mx-4 text-lg">
{{ accessStore.userRoles?.[0] }} {{ userStore.userRoles?.[0] }}
</span> </span>
</div> </div>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,15 +1,15 @@
import { createPinia, setActivePinia } from 'pinia'; import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest'; import { beforeEach, describe, expect, it } from 'vitest';
import { useCoreAccessStore } from './access'; import { useAccessStore } from './access';
describe('useCoreAccessStore', () => { describe('useAccessStore', () => {
beforeEach(() => { beforeEach(() => {
setActivePinia(createPinia()); setActivePinia(createPinia());
}); });
it('updates accessMenus state', () => { it('updates accessMenus state', () => {
const store = useCoreAccessStore(); const store = useAccessStore();
expect(store.accessMenus).toEqual([]); expect(store.accessMenus).toEqual([]);
store.setAccessMenus([{ name: 'Dashboard', path: '/dashboard' }]); store.setAccessMenus([{ name: 'Dashboard', path: '/dashboard' }]);
expect(store.accessMenus).toEqual([ 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', () => { it('updates accessToken state correctly', () => {
const store = useCoreAccessStore(); const store = useAccessStore();
expect(store.accessToken).toBeNull(); // 初始状态 expect(store.accessToken).toBeNull(); // 初始状态
store.setAccessToken('abc123'); store.setAccessToken('abc123');
expect(store.accessToken).toBe('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', () => { it('returns the correct accessToken', () => {
const store = useCoreAccessStore(); const store = useAccessStore();
store.setAccessToken('xyz789'); store.setAccessToken('xyz789');
expect(store.accessToken).toBe('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', () => { it('handles empty accessMenus correctly', () => {
const store = useCoreAccessStore(); const store = useAccessStore();
store.setAccessMenus([]); store.setAccessMenus([]);
expect(store.accessMenus).toEqual([]); expect(store.accessMenus).toEqual([]);
}); });
// 测试设置空的访问路由列表 // 测试设置空的访问路由列表
it('handles empty accessRoutes correctly', () => { it('handles empty accessRoutes correctly', () => {
const store = useCoreAccessStore(); const store = useAccessStore();
store.setAccessRoutes([]); store.setAccessRoutes([]);
expect(store.accessRoutes).toEqual([]); expect(store.accessRoutes).toEqual([]);
}); });

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,7 +7,7 @@ import { openWindow, startProgress, stopProgress } from '@vben-core/shared';
import { acceptHMRUpdate, defineStore } from 'pinia'; import { acceptHMRUpdate, defineStore } from 'pinia';
interface TabsState { interface TabbarState {
/** /**
* @zh_CN * @zh_CN
*/ */
@ -37,7 +37,7 @@ interface TabsState {
/** /**
* @zh_CN 访 * @zh_CN 访
*/ */
export const useCoreTabbarStore = defineStore('core-tabbar', { export const useTabbarStore = defineStore('core-tabbar', {
actions: { actions: {
/** /**
* Close tabs in bulk * Close tabs in bulk
@ -441,7 +441,7 @@ export const useCoreTabbarStore = defineStore('core-tabbar', {
storage: sessionStorage, storage: sessionStorage,
}, },
], ],
state: (): TabsState => ({ state: (): TabbarState => ({
cachedTabs: new Set(), cachedTabs: new Set(),
dragEndIndex: 0, dragEndIndex: 0,
excludeCachedTabs: new Set(), excludeCachedTabs: new Set(),
@ -454,7 +454,7 @@ export const useCoreTabbarStore = defineStore('core-tabbar', {
// 解决热更新问题 // 解决热更新问题
const hot = import.meta.hot; const hot = import.meta.hot;
if (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 { Pinia } from 'pinia';
import type { App } from 'vue';
import { createPinia } from 'pinia'; import { createPinia } from 'pinia';
let pinia: Pinia; let pinia: Pinia;
@ -14,7 +16,7 @@ export interface InitStoreOptions {
/** /**
* @zh_CN pinia * @zh_CN pinia
*/ */
export async function initStore(options: InitStoreOptions) { export async function initStores(app: App, options: InitStoreOptions) {
const { createPersistedState } = await import('pinia-plugin-persistedstate'); const { createPersistedState } = await import('pinia-plugin-persistedstate');
pinia = createPinia(); pinia = createPinia();
const { namespace } = options; const { namespace } = options;
@ -25,6 +27,7 @@ export async function initStore(options: InitStoreOptions) {
storage: localStorage, storage: localStorage,
}), }),
); );
app.use(pinia);
return pinia; return pinia;
} }

View File

@ -3,4 +3,5 @@ export * from './generate-menus';
export * from './generate-routes-backend'; export * from './generate-routes-backend';
export * from './generate-routes-frontend'; export * from './generate-routes-frontend';
export * from './merge-route-modules'; export * from './merge-route-modules';
export * from './reset-routes';
export * from './unmount-global-loading'; 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);
}
});
}

8
pnpm-lock.yaml generated
View File

@ -690,6 +690,9 @@ importers:
vue: vue:
specifier: ^3.4.34 specifier: ^3.4.34
version: 3.4.34(typescript@5.5.4) version: 3.4.34(typescript@5.5.4)
vue-router:
specifier: ^4.4.0
version: 4.4.0(vue@3.4.34(typescript@5.5.4))
packages/effects/chart-ui: packages/effects/chart-ui:
dependencies: dependencies:
@ -3081,6 +3084,7 @@ packages:
'@ls-lint/ls-lint@2.2.3': '@ls-lint/ls-lint@2.2.3':
resolution: {integrity: sha512-ekM12jNm/7O2I/hsRv9HvYkRdfrHpiV1epVuI2NP+eTIcEgdIdKkKCs9KgQydu/8R5YXTov9aHdOgplmCHLupw==} resolution: {integrity: sha512-ekM12jNm/7O2I/hsRv9HvYkRdfrHpiV1epVuI2NP+eTIcEgdIdKkKCs9KgQydu/8R5YXTov9aHdOgplmCHLupw==}
cpu: [x64, arm64, s390x]
os: [darwin, linux, win32] os: [darwin, linux, win32]
hasBin: true hasBin: true
@ -5288,7 +5292,7 @@ packages:
resolution: {integrity: sha512-/UbPA+bYY7nIxcjL3kpcDY3UNdoLHFhyBFzHox2M0ypcUoueTn6woZUUmzzi5et/dXChksasYYFeKE2wshOrhg==} resolution: {integrity: sha512-/UbPA+bYY7nIxcjL3kpcDY3UNdoLHFhyBFzHox2M0ypcUoueTn6woZUUmzzi5et/dXChksasYYFeKE2wshOrhg==}
engines: {node: '>=16'} engines: {node: '>=16'}
peerDependencies: peerDependencies:
eslint: ^8.56.0 || ^9.0.0-0 eslint: ^9.7.0
eslint-plugin-jsdoc@48.9.2: eslint-plugin-jsdoc@48.9.2:
resolution: {integrity: sha512-ydqg2lEY/WxhMXEb1ZAn+yRbc43DlKYdMP/nUreF5ODE1P9mgeff8atL16lYNNKOvYxNOzL85/5gFVeGylSioA==} resolution: {integrity: sha512-ydqg2lEY/WxhMXEb1ZAn+yRbc43DlKYdMP/nUreF5ODE1P9mgeff8atL16lYNNKOvYxNOzL85/5gFVeGylSioA==}
@ -5360,7 +5364,7 @@ packages:
resolution: {integrity: sha512-n3AKiVpY2/uDcGrS3+QsYDkjPfaOrNrsfQxU9nt5nitd9KuvVXrfAvgCO9DYPSfap+Gqjw9EOrXIsBp5tlHZjA==} resolution: {integrity: sha512-n3AKiVpY2/uDcGrS3+QsYDkjPfaOrNrsfQxU9nt5nitd9KuvVXrfAvgCO9DYPSfap+Gqjw9EOrXIsBp5tlHZjA==}
engines: {node: '>=18.18'} engines: {node: '>=18.18'}
peerDependencies: peerDependencies:
eslint: '>=8.56.0' eslint: ^8.57.0
eslint-plugin-unused-imports@4.0.1: eslint-plugin-unused-imports@4.0.1:
resolution: {integrity: sha512-rax76s05z64uQgG9YXsWFmXrgjkaK79AvfeAWiSxhPP6RVGxeRaj4+2u+wxxu/mDy2pmJoOy1QTOEALMia2xGQ==} resolution: {integrity: sha512-rax76s05z64uQgG9YXsWFmXrgjkaK79AvfeAWiSxhPP6RVGxeRaj4+2u+wxxu/mDy2pmJoOy1QTOEALMia2xGQ==}

View File

@ -168,10 +168,11 @@ import type { HttpResponse } from '@vben/request';
import { useAppConfig } from '@vben/hooks'; import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences'; import { preferences } from '@vben/preferences';
import { RequestClient } from '@vben/request'; import { RequestClient } from '@vben/request';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue'; import { message } from 'ant-design-vue';
import { useAccessStore } from '#/store'; import { useAuthStore } from '#/store';
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
@ -192,13 +193,14 @@ function createRequestClient(baseURL: string) {
}, },
unAuthorizedHandler: async () => { unAuthorizedHandler: async () => {
const accessStore = useAccessStore(); const accessStore = useAccessStore();
const authStore = useAuthStore();
accessStore.setAccessToken(null); accessStore.setAccessToken(null);
if (preferences.app.loginExpiredMode === 'modal') { if (preferences.app.loginExpiredMode === 'modal') {
accessStore.openLoginExpiredModal = true; accessStore.setLoginExpired(true);
} else { } else {
// 退出登录 // 退出登录
await accessStore.logout(); await authStore.logout();
} }
}, },
}; };

View File

@ -47,12 +47,12 @@ export const overridesPreferences = defineOverridesPreferences({
- 确保接口返回的角色和路由表的权限匹配 - 确保接口返回的角色和路由表的权限匹配
可查看应用下的 `src/store/modules/access`,找到下面代码, 可查看应用下的 `src/store/auth`,找到下面代码,
```ts ```ts
// 设置登录用户信息,需要确保 userInfo.roles 是一个数组,且包含路由表中的权限 // 设置登录用户信息,需要确保 userInfo.roles 是一个数组,且包含路由表中的权限
// 例如userInfo.roles=['super', 'admin'] // 例如userInfo.roles=['super', 'admin']
coreStoreAccess.setUserInfo(userInfo); authStore.setUserInfo(userInfo);
``` ```
到这里,就已经配置完成,你需要确保登录后,接口返回的角色和路由表的权限匹配,否则无法访问。 到这里,就已经配置完成,你需要确保登录后,接口返回的角色和路由表的权限匹配,否则无法访问。
@ -157,19 +157,17 @@ const dashboardMenus = [
### 权限码 ### 权限码
权限码为接口返回的权限码,通过权限码来判断按钮是否显示,逻辑在`src/store/modules/access`下: 权限码为接口返回的权限码,通过权限码来判断按钮是否显示,逻辑在`src/store/auth`下:
```ts ```ts
// 获取用户信息并存储到 accessStore 中
// Get user information and store it in accessStore
const [fetchUserInfoResult, accessCodes] = await Promise.all([ const [fetchUserInfoResult, accessCodes] = await Promise.all([
fetchUserInfo(), fetchUserInfo(),
getAccessCodes(), getAccessCodes(),
]); ]);
userInfo = fetchUserInfoResult; userInfo = fetchUserInfoResult;
coreStoreAccess.setUserInfo(userInfo); authStore.setUserInfo(userInfo);
coreStoreAccess.setAccessCodes(accessCodes); accessStore.setAccessCodes(accessCodes);
``` ```
找到 `getAccessCodes` 对应的接口,可根据业务逻辑进行调整。 找到 `getAccessCodes` 对应的接口,可根据业务逻辑进行调整。