mirror of
https://github.com/vbenjs/vue-vben-admin.git
synced 2025-01-23 01:30:26 +08:00
refactor: Separate store
This commit is contained in:
parent
cf0ec053e4
commit
89dcf522f5
@ -6,10 +6,11 @@ import type { HttpResponse } from '@vben/request';
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { RequestClient } from '@vben/request';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import { useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
@ -30,13 +31,14 @@ function createRequestClient(baseURL: string) {
|
||||
},
|
||||
unAuthorizedHandler: async () => {
|
||||
const accessStore = useAccessStore();
|
||||
const authStore = useAuthStore();
|
||||
accessStore.setAccessToken(null);
|
||||
|
||||
if (preferences.app.loginExpiredMode === 'modal') {
|
||||
accessStore.openLoginExpiredModal = true;
|
||||
accessStore.setLoginExpired(true);
|
||||
} else {
|
||||
// 退出登录
|
||||
await accessStore.logout();
|
||||
await authStore.logout();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
@ -1,11 +1,11 @@
|
||||
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/antd';
|
||||
|
||||
import { setupI18n } from '#/locales';
|
||||
import { setupStore } from '#/store';
|
||||
|
||||
import App from './app.vue';
|
||||
import { router } from './router';
|
||||
@ -17,10 +17,10 @@ async function bootstrap(namespace: string) {
|
||||
await setupI18n(app);
|
||||
|
||||
// 配置 pinia-tore
|
||||
await setupStore(app, { namespace });
|
||||
await initStores(app, { namespace });
|
||||
|
||||
// 安装权限指令
|
||||
useAccessDirective(app);
|
||||
registerAccessDirective(app);
|
||||
|
||||
// 配置路由及路由守卫
|
||||
app.use(router);
|
||||
|
@ -13,11 +13,17 @@ import {
|
||||
UserDropdown,
|
||||
} from '@vben/layouts';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import {
|
||||
resetAllStores,
|
||||
storeToRefs,
|
||||
useAccessStore,
|
||||
useUserStore,
|
||||
} from '@vben/stores';
|
||||
import { openWindow } from '@vben/utils';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
import { resetRoutes } from '#/router';
|
||||
import { resetAllStores, storeToRefs, useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
const notifications = ref<NotificationItem[]>([
|
||||
{
|
||||
@ -50,6 +56,9 @@ const notifications = ref<NotificationItem[]>([
|
||||
},
|
||||
]);
|
||||
|
||||
const userStore = useUserStore();
|
||||
const authStore = useAuthStore();
|
||||
const accessStore = useAccessStore();
|
||||
const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
@ -84,16 +93,10 @@ const menus = computed(() => [
|
||||
},
|
||||
]);
|
||||
|
||||
const accessStore = useAccessStore();
|
||||
|
||||
const {
|
||||
loading: loginLoading,
|
||||
openLoginExpiredModal,
|
||||
userInfo,
|
||||
} = storeToRefs(accessStore);
|
||||
const { loginLoading } = storeToRefs(authStore);
|
||||
|
||||
const avatar = computed(() => {
|
||||
return userInfo.value?.avatar ?? preferences.app.defaultAvatar;
|
||||
return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
@ -119,7 +122,7 @@ function handleMakeAll() {
|
||||
<UserDropdown
|
||||
:avatar
|
||||
:menus
|
||||
:text="userInfo?.realName"
|
||||
:text="userStore.userInfo?.realName"
|
||||
description="ann.vben@gmail.com"
|
||||
tag-text="Pro"
|
||||
@logout="handleLogout"
|
||||
@ -135,12 +138,12 @@ function handleMakeAll() {
|
||||
</template>
|
||||
<template #extra>
|
||||
<AuthenticationLoginExpiredModal
|
||||
v-model:open="openLoginExpiredModal"
|
||||
v-model:open="accessStore.loginExpired"
|
||||
:avatar
|
||||
:loading="loginLoading"
|
||||
password-placeholder="123456"
|
||||
username-placeholder="vben"
|
||||
@submit="accessStore.authLogin"
|
||||
@submit="authStore.authLogin"
|
||||
/>
|
||||
</template>
|
||||
<template #lock-screen>
|
||||
|
@ -2,13 +2,14 @@ import type { Router } from 'vue-router';
|
||||
|
||||
import { LOGIN_PATH } from '@vben/constants';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { useAccessStore, useUserStore } from '@vben/stores';
|
||||
import { startProgress, stopProgress } from '@vben/utils';
|
||||
|
||||
import { useTitle } from '@vueuse/core';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
import { coreRouteNames, dynamicRoutes } from '#/router/routes';
|
||||
import { useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
import { generateAccess } from './access';
|
||||
|
||||
@ -58,10 +59,11 @@ function setupCommonGuard(router: Router) {
|
||||
function setupAccessGuard(router: Router) {
|
||||
router.beforeEach(async (to, from) => {
|
||||
const accessStore = useAccessStore();
|
||||
const accessToken = accessStore.accessToken;
|
||||
const userStore = useUserStore();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// accessToken 检查
|
||||
if (!accessToken) {
|
||||
if (!accessStore.accessToken) {
|
||||
if (
|
||||
// 基本路由,这些路由不需要进入权限拦截
|
||||
coreRouteNames.includes(to.name as string) ||
|
||||
@ -93,8 +95,7 @@ function setupAccessGuard(router: Router) {
|
||||
|
||||
// 生成路由表
|
||||
// 当前登录用户拥有的角色标识列表
|
||||
const userInfo =
|
||||
accessStore.userInfo || (await accessStore.fetchUserInfo());
|
||||
const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());
|
||||
const userRoles = userInfo.roles ?? [];
|
||||
|
||||
// 生成菜单和路由
|
||||
|
@ -1,12 +1,10 @@
|
||||
import type { RouteRecordName, RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import {
|
||||
createRouter,
|
||||
createWebHashHistory,
|
||||
createWebHistory,
|
||||
} from 'vue-router';
|
||||
|
||||
import { traverseTreeValues } from '@vben/utils';
|
||||
import { resetStaticRoutes } from '@vben/utils';
|
||||
|
||||
import { createRouterGuard } from './guard';
|
||||
import { routes } from './routes';
|
||||
@ -26,33 +24,8 @@ const router = createRouter({
|
||||
// strict: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* @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 resetRoutes = () => resetStaticRoutes(router, routes);
|
||||
|
||||
const { getRoutes, hasRoute, removeRoute } = router;
|
||||
const allRoutes = getRoutes();
|
||||
allRoutes.forEach(({ name }) => {
|
||||
// 存在于路由表且非白名单才需要删除
|
||||
if (name && !staticRouteNames.includes(name) && hasRoute(name)) {
|
||||
removeRoute(name);
|
||||
}
|
||||
});
|
||||
}
|
||||
// 创建路由守卫
|
||||
createRouterGuard(router);
|
||||
|
||||
|
@ -1,12 +1,11 @@
|
||||
import type { LoginAndRegisterParams } from '@vben/common-ui';
|
||||
import type { MenuRecordRaw, UserInfo } from '@vben/types';
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
import type { UserInfo } from '@vben/types';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
import { ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
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 { defineStore } from 'pinia';
|
||||
@ -14,31 +13,12 @@ import { defineStore } from 'pinia';
|
||||
import { getAccessCodes, getUserInfo, login } from '#/api';
|
||||
import { $t } from '#/locales';
|
||||
|
||||
export const useAccessStore = defineStore('access', () => {
|
||||
const coreStoreAccess = useCoreAccessStore();
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const accessStore = useAccessStore();
|
||||
const userStore = useUserStore();
|
||||
const router = useRouter();
|
||||
|
||||
const loading = 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);
|
||||
}
|
||||
const loginLoading = ref(false);
|
||||
|
||||
/**
|
||||
* 异步处理登录操作
|
||||
@ -52,19 +32,16 @@ export const useAccessStore = defineStore('access', () => {
|
||||
// 异步处理用户登录操作并获取 accessToken
|
||||
let userInfo: null | UserInfo = null;
|
||||
try {
|
||||
loading.value = true;
|
||||
loginLoading.value = true;
|
||||
const { accessToken, refreshToken } = await login(params);
|
||||
|
||||
// 如果成功获取到 accessToken
|
||||
// If accessToken is successfully obtained
|
||||
if (accessToken) {
|
||||
// 将 accessToken 存储到 accessStore 中
|
||||
// Store the accessToken in accessStore
|
||||
coreStoreAccess.setAccessToken(accessToken);
|
||||
coreStoreAccess.setRefreshToken(refreshToken);
|
||||
accessStore.setAccessToken(accessToken);
|
||||
accessStore.setRefreshToken(refreshToken);
|
||||
|
||||
// 获取用户信息并存储到 accessStore 中
|
||||
// Get user information and store it in accessStore
|
||||
const [fetchUserInfoResult, accessCodes] = await Promise.all([
|
||||
fetchUserInfo(),
|
||||
getAccessCodes(),
|
||||
@ -72,11 +49,11 @@ export const useAccessStore = defineStore('access', () => {
|
||||
|
||||
userInfo = fetchUserInfoResult;
|
||||
|
||||
coreStoreAccess.setUserInfo(userInfo);
|
||||
coreStoreAccess.setAccessCodes(accessCodes);
|
||||
userStore.setUserInfo(userInfo);
|
||||
accessStore.setAccessCodes(accessCodes);
|
||||
|
||||
if (openLoginExpiredModal.value) {
|
||||
openLoginExpiredModal.value = false;
|
||||
if (accessStore.loginExpired) {
|
||||
accessStore.setLoginExpired(false);
|
||||
} else {
|
||||
onSuccess
|
||||
? await onSuccess?.()
|
||||
@ -92,18 +69,17 @@ export const useAccessStore = defineStore('access', () => {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
loginLoading.value = false;
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
userInfo,
|
||||
};
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
resetAllStores();
|
||||
openLoginExpiredModal.value = false;
|
||||
accessStore.setLoginExpired(false);
|
||||
|
||||
// 回登陆页带上当前路由地址
|
||||
await router.replace({
|
||||
@ -117,29 +93,19 @@ export const useAccessStore = defineStore('access', () => {
|
||||
async function fetchUserInfo() {
|
||||
let userInfo: null | UserInfo = null;
|
||||
userInfo = await getUserInfo();
|
||||
coreStoreAccess.setUserInfo(userInfo);
|
||||
userStore.setUserInfo(userInfo);
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
function $reset() {
|
||||
loading.value = false;
|
||||
openLoginExpiredModal.value = false;
|
||||
loginLoading.value = false;
|
||||
}
|
||||
|
||||
return {
|
||||
$reset,
|
||||
accessRoutes,
|
||||
accessToken,
|
||||
authLogin,
|
||||
fetchUserInfo,
|
||||
loading,
|
||||
loginLoading,
|
||||
logout,
|
||||
openLoginExpiredModal,
|
||||
refreshToken,
|
||||
setAccessMenus,
|
||||
setAccessRoutes,
|
||||
setAccessToken,
|
||||
userInfo,
|
||||
userRoles,
|
||||
};
|
||||
});
|
@ -1,18 +1 @@
|
||||
import type { InitStoreOptions } from '@vben/stores';
|
||||
|
||||
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';
|
||||
export * from './auth';
|
||||
|
@ -1,18 +1,18 @@
|
||||
<script lang="ts" setup>
|
||||
import { AuthenticationLogin } from '@vben/common-ui';
|
||||
|
||||
import { useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
defineOptions({ name: 'Login' });
|
||||
|
||||
const accessStore = useAccessStore();
|
||||
const authStore = useAuthStore();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AuthenticationLogin
|
||||
:loading="accessStore.loading"
|
||||
:loading="authStore.loginLoading"
|
||||
password-placeholder="123456"
|
||||
username-placeholder="vben"
|
||||
@submit="accessStore.authLogin"
|
||||
@submit="authStore.authLogin"
|
||||
/>
|
||||
</template>
|
||||
|
@ -17,12 +17,11 @@ import {
|
||||
WorkbenchTrends,
|
||||
} from '@vben/common-ui';
|
||||
import { preferences } from '@vben/preferences';
|
||||
|
||||
import { useAccessStore } from '#/store';
|
||||
import { useUserStore } from '@vben/stores';
|
||||
|
||||
import AnalyticsVisitsSource from '../analytics/analytics-visits-source.vue';
|
||||
|
||||
const accessStore = useAccessStore();
|
||||
const userStore = useUserStore();
|
||||
|
||||
const projectItems: WorkbenchProjectItem[] = [
|
||||
{
|
||||
@ -201,10 +200,10 @@ const trendItems: WorkbenchTrendItem[] = [
|
||||
<template>
|
||||
<div class="p-5">
|
||||
<WorkbenchHeader
|
||||
:avatar="accessStore.userInfo?.avatar || preferences.app.defaultAvatar"
|
||||
:avatar="userStore.userInfo?.avatar || preferences.app.defaultAvatar"
|
||||
>
|
||||
<template #title>
|
||||
早安, {{ accessStore.userInfo?.realName }}, 开始您一天的工作吧!
|
||||
早安, {{ userStore.userInfo?.realName }}, 开始您一天的工作吧!
|
||||
</template>
|
||||
<template #description> 今日晴,20℃ - 32℃! </template>
|
||||
</WorkbenchHeader>
|
||||
|
@ -4,10 +4,11 @@ import type { LoginAndRegisterParams } from '@vben/common-ui';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { AccessControl, useAccess } from '@vben/access';
|
||||
import { resetAllStores, useUserStore } from '@vben/stores';
|
||||
|
||||
import { Button } from 'ant-design-vue';
|
||||
|
||||
import { resetAllStores, useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
const accounts: Record<string, LoginAndRegisterParams> = {
|
||||
admin: {
|
||||
@ -25,21 +26,22 @@ const accounts: Record<string, LoginAndRegisterParams> = {
|
||||
};
|
||||
|
||||
const { accessMode, hasAccessByCodes } = useAccess();
|
||||
const accessStore = useAccessStore();
|
||||
const authStore = useAuthStore();
|
||||
const userStore = useUserStore();
|
||||
const router = useRouter();
|
||||
|
||||
function roleButtonType(role: string) {
|
||||
return accessStore.userRoles.includes(role) ? 'primary' : 'default';
|
||||
return userStore.userRoles.includes(role) ? 'primary' : 'default';
|
||||
}
|
||||
|
||||
async function changeAccount(role: string) {
|
||||
if (accessStore.userRoles.includes(role)) {
|
||||
if (userStore.userRoles.includes(role)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const account = accounts[role];
|
||||
resetAllStores();
|
||||
await accessStore.authLogin(account, async () => {
|
||||
await authStore.authLogin(account, async () => {
|
||||
router.go(0);
|
||||
});
|
||||
}
|
||||
@ -58,7 +60,7 @@ async function changeAccount(role: string) {
|
||||
<div class="mb-3">
|
||||
<span class="text-lg font-semibold">当前角色:</span>
|
||||
<span class="text-primary mx-4 text-lg">
|
||||
{{ accessStore.userRoles?.[0] }}
|
||||
{{ userStore.userRoles?.[0] }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
@ -4,10 +4,11 @@ import type { LoginAndRegisterParams } from '@vben/common-ui';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { useAccess } from '@vben/access';
|
||||
import { resetAllStores, useUserStore } from '@vben/stores';
|
||||
|
||||
import { Button } from 'ant-design-vue';
|
||||
|
||||
import { resetAllStores, useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
const accounts: Record<string, LoginAndRegisterParams> = {
|
||||
admin: {
|
||||
@ -25,15 +26,16 @@ const accounts: Record<string, LoginAndRegisterParams> = {
|
||||
};
|
||||
|
||||
const { accessMode, toggleAccessMode } = useAccess();
|
||||
const accessStore = useAccessStore();
|
||||
const userStore = useUserStore();
|
||||
const accessStore = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
function roleButtonType(role: string) {
|
||||
return accessStore.userRoles.includes(role) ? 'primary' : 'default';
|
||||
return userStore.userRoles.includes(role) ? 'primary' : 'default';
|
||||
}
|
||||
|
||||
async function changeAccount(role: string) {
|
||||
if (accessStore.userRoles.includes(role)) {
|
||||
if (userStore.userRoles.includes(role)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -80,7 +82,7 @@ async function handleToggleAccessMode() {
|
||||
<div class="mb-3">
|
||||
<span class="text-lg font-semibold">当前账号:</span>
|
||||
<span class="text-primary mx-4 text-lg">
|
||||
{{ accessStore.userRoles?.[0] }}
|
||||
{{ userStore.userRoles?.[0] }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
@ -33,6 +33,6 @@ const authDirective: Directive = {
|
||||
mounted,
|
||||
};
|
||||
|
||||
export function useAccessDirective(app: App) {
|
||||
export function registerAccessDirective(app: App) {
|
||||
app.directive('access', authDirective);
|
||||
}
|
||||
|
@ -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;
|
||||
|
@ -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 {
|
||||
|
@ -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;
|
||||
|
@ -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();
|
||||
|
@ -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>
|
||||
|
||||
|
@ -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>
|
||||
|
@ -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);
|
||||
|
@ -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>('');
|
||||
|
@ -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"
|
||||
/>
|
||||
|
@ -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 },
|
||||
);
|
||||
|
@ -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) {
|
||||
|
@ -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() {
|
||||
|
@ -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
|
||||
|
@ -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([]);
|
||||
});
|
||||
|
@ -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));
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
export * from './access';
|
||||
export * from './lock';
|
||||
export * from './tabbar';
|
||||
export * from './user';
|
||||
|
@ -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);
|
||||
|
@ -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;
|
||||
|
@ -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' },
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
/**
|
||||
|
37
packages/stores/src/modules/user.test.ts
Normal file
37
packages/stores/src/modules/user.test.ts
Normal 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([]);
|
||||
});
|
||||
});
|
63
packages/stores/src/modules/user.ts
Normal file
63
packages/stores/src/modules/user.ts
Normal 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));
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
|
@ -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';
|
||||
|
31
packages/utils/src/helpers/reset-routes.ts
Normal file
31
packages/utils/src/helpers/reset-routes.ts
Normal 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
8
pnpm-lock.yaml
generated
@ -690,6 +690,9 @@ importers:
|
||||
vue:
|
||||
specifier: ^3.4.34
|
||||
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:
|
||||
dependencies:
|
||||
@ -3081,6 +3084,7 @@ packages:
|
||||
|
||||
'@ls-lint/ls-lint@2.2.3':
|
||||
resolution: {integrity: sha512-ekM12jNm/7O2I/hsRv9HvYkRdfrHpiV1epVuI2NP+eTIcEgdIdKkKCs9KgQydu/8R5YXTov9aHdOgplmCHLupw==}
|
||||
cpu: [x64, arm64, s390x]
|
||||
os: [darwin, linux, win32]
|
||||
hasBin: true
|
||||
|
||||
@ -5288,7 +5292,7 @@ packages:
|
||||
resolution: {integrity: sha512-/UbPA+bYY7nIxcjL3kpcDY3UNdoLHFhyBFzHox2M0ypcUoueTn6woZUUmzzi5et/dXChksasYYFeKE2wshOrhg==}
|
||||
engines: {node: '>=16'}
|
||||
peerDependencies:
|
||||
eslint: ^8.56.0 || ^9.0.0-0
|
||||
eslint: ^9.7.0
|
||||
|
||||
eslint-plugin-jsdoc@48.9.2:
|
||||
resolution: {integrity: sha512-ydqg2lEY/WxhMXEb1ZAn+yRbc43DlKYdMP/nUreF5ODE1P9mgeff8atL16lYNNKOvYxNOzL85/5gFVeGylSioA==}
|
||||
@ -5360,7 +5364,7 @@ packages:
|
||||
resolution: {integrity: sha512-n3AKiVpY2/uDcGrS3+QsYDkjPfaOrNrsfQxU9nt5nitd9KuvVXrfAvgCO9DYPSfap+Gqjw9EOrXIsBp5tlHZjA==}
|
||||
engines: {node: '>=18.18'}
|
||||
peerDependencies:
|
||||
eslint: '>=8.56.0'
|
||||
eslint: ^8.57.0
|
||||
|
||||
eslint-plugin-unused-imports@4.0.1:
|
||||
resolution: {integrity: sha512-rax76s05z64uQgG9YXsWFmXrgjkaK79AvfeAWiSxhPP6RVGxeRaj4+2u+wxxu/mDy2pmJoOy1QTOEALMia2xGQ==}
|
||||
|
@ -168,10 +168,11 @@ import type { HttpResponse } from '@vben/request';
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { RequestClient } from '@vben/request';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import { useAccessStore } from '#/store';
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
@ -192,13 +193,14 @@ function createRequestClient(baseURL: string) {
|
||||
},
|
||||
unAuthorizedHandler: async () => {
|
||||
const accessStore = useAccessStore();
|
||||
const authStore = useAuthStore();
|
||||
accessStore.setAccessToken(null);
|
||||
|
||||
if (preferences.app.loginExpiredMode === 'modal') {
|
||||
accessStore.openLoginExpiredModal = true;
|
||||
accessStore.setLoginExpired(true);
|
||||
} else {
|
||||
// 退出登录
|
||||
await accessStore.logout();
|
||||
await authStore.logout();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
@ -47,12 +47,12 @@ export const overridesPreferences = defineOverridesPreferences({
|
||||
|
||||
- 确保接口返回的角色和路由表的权限匹配
|
||||
|
||||
可查看应用下的 `src/store/modules/access`,找到下面代码,
|
||||
可查看应用下的 `src/store/auth`,找到下面代码,
|
||||
|
||||
```ts
|
||||
// 设置登录用户信息,需要确保 userInfo.roles 是一个数组,且包含路由表中的权限
|
||||
// 例如:userInfo.roles=['super', 'admin']
|
||||
coreStoreAccess.setUserInfo(userInfo);
|
||||
authStore.setUserInfo(userInfo);
|
||||
```
|
||||
|
||||
到这里,就已经配置完成,你需要确保登录后,接口返回的角色和路由表的权限匹配,否则无法访问。
|
||||
@ -157,19 +157,17 @@ const dashboardMenus = [
|
||||
|
||||
### 权限码
|
||||
|
||||
权限码为接口返回的权限码,通过权限码来判断按钮是否显示,逻辑在`src/store/modules/access`下:
|
||||
权限码为接口返回的权限码,通过权限码来判断按钮是否显示,逻辑在`src/store/auth`下:
|
||||
|
||||
```ts
|
||||
// 获取用户信息并存储到 accessStore 中
|
||||
// Get user information and store it in accessStore
|
||||
const [fetchUserInfoResult, accessCodes] = await Promise.all([
|
||||
fetchUserInfo(),
|
||||
getAccessCodes(),
|
||||
]);
|
||||
|
||||
userInfo = fetchUserInfoResult;
|
||||
coreStoreAccess.setUserInfo(userInfo);
|
||||
coreStoreAccess.setAccessCodes(accessCodes);
|
||||
authStore.setUserInfo(userInfo);
|
||||
accessStore.setAccessCodes(accessCodes);
|
||||
```
|
||||
|
||||
找到 `getAccessCodes` 对应的接口,可根据业务逻辑进行调整。
|
||||
|
Loading…
Reference in New Issue
Block a user