perf: Improve the use of store in the app

This commit is contained in:
vince 2024-07-05 23:15:46 +08:00
parent ad6ae1d21d
commit 8042e2b044
39 changed files with 387 additions and 224 deletions

View File

@ -51,16 +51,25 @@ export class MockService implements OnModuleInit {
// 密码哈希
const hashPassword = await bcrypt.hash('123456', 10);
await this.addItem('users', {
id: 0,
password: hashPassword,
realName: 'Vben',
roles: ['admin'],
roles: ['super'],
username: 'vben',
});
await this.addItem('users', {
id: 1,
password: hashPassword,
realName: 'Admin',
roles: ['admin'],
username: 'admin',
});
await this.addItem('users', {
id: 2,
password: hashPassword,
realName: 'Jack',
roles: ['user'],
username: 'jack',

View File

@ -5,7 +5,7 @@
import type { AxiosResponse } from '@vben-core/request';
import { RequestClient, isCancelError } from '@vben-core/request';
import { useAccessStore } from '@vben-core/stores';
import { useCoreAccessStore } from '@vben-core/stores';
import { message } from 'ant-design-vue';
@ -30,7 +30,8 @@ function createRequestClient() {
makeAuthorization: () => {
return {
handler: () => {
const accessStore = useAccessStore();
// 这里不能用 useAccessStore因为 useAccessStore 会导致循环引用
const accessStore = useCoreAccessStore();
return {
refreshToken: `Bearer ${accessStore.getRefreshToken}`,
token: `Bearer ${accessStore.getAccessToken}`,

View File

@ -4,16 +4,16 @@ import type { NotificationItem } from '@vben/widgets';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { IcRoundCreditScore, MdiDriveDocument, MdiGithub } from '@vben/icons';
import { BasicLayout } from '@vben/layouts';
import { $t } from '@vben/locales';
import { openWindow } from '@vben/utils';
import { Notification, UserDropdown } from '@vben/widgets';
import { preferences } from '@vben-core/preferences';
import { useRequest } from '@vben-core/request';
import { useAccessStore } from '@vben-core/stores';
import { getUserInfo } from '#/apis';
import { resetRoutes } from '#/router';
import { useAppStore } from '#/store';
// https://avatar.vercel.sh/vercel.svg?text=Vaa
// https://avatar.vercel.sh/1
@ -80,20 +80,22 @@ const menus = computed(() => [
},
]);
const accessStore = useAccessStore();
const appStore = useAppStore();
const router = useRouter();
// //
// //
// const { runAsync: runGetUserInfo } = useRequest(getUserInfo, {
// manual: true,
// });
const { runAsync: runGetUserInfo } = useRequest(getUserInfo, {
manual: true,
});
// runGetUserInfo().then((userInfo) => {
// accessStore.setUserInfo(userInfo);
// });
runGetUserInfo().then((userInfo) => {
accessStore.setUserInfo(userInfo);
});
function handleLogout() {
accessStore.$reset();
router.replace('/auth/login');
async function handleLogout() {
await appStore.resetAppState();
resetRoutes();
router.replace(LOGIN_PATH);
}
function handleNoticeClear() {

View File

@ -4,12 +4,12 @@ import { LOGIN_PATH } from '@vben/constants';
import { $t } from '@vben/locales';
import { startProgress, stopProgress } from '@vben/utils';
import { preferences } from '@vben-core/preferences';
import { useAccessStore } from '@vben-core/stores';
import { useTitle } from '@vueuse/core';
import { generateAccess } from '#/forward/access';
import { dynamicRoutes, essentialsRouteNames } from '#/router/routes';
import { useAccessStore } from '#/store';
/**
*
@ -57,7 +57,7 @@ function setupCommonGuard(router: Router) {
function setupAccessGuard(router: Router) {
router.beforeEach(async (to, from) => {
const accessStore = useAccessStore();
const accessToken = accessStore.getAccessToken;
const accessToken = accessStore.accessToken;
// accessToken 检查
if (!accessToken) {
@ -83,7 +83,7 @@ function setupAccessGuard(router: Router) {
return to;
}
const accessRoutes = accessStore.getAccessRoutes;
const accessRoutes = accessStore.accessRoutes;
// 是否已经生成过动态路由
if (accessRoutes && accessRoutes.length > 0) {
@ -92,7 +92,10 @@ function setupAccessGuard(router: Router) {
// 生成路由表
// 当前登录用户拥有的角色标识列表
const userRoles = accessStore.getUserRoles;
const userInfo =
accessStore.userInfo || (await accessStore.fetchUserInfo());
const userRoles = userInfo.roles ?? [];
// 生成菜单和路由
const { accessibleMenus, accessibleRoutes } = await generateAccess({

View File

@ -77,6 +77,17 @@ const routes: RouteRecordRaw[] = [
title: $t('page.demos.access.access-test-2'),
},
},
{
name: 'AccessFrontendTest3',
path: 'access-test-3',
component: () =>
import('#/views/demos/access/frontend/access-test-3.vue'),
meta: {
authority: ['super'],
icon: 'mdi:button-cursor',
title: $t('page.demos.access.access-test-3'),
},
},
],
},
{

View File

@ -2,7 +2,7 @@ import type { InitStoreOptions } from '@vben-core/stores';
import type { App } from 'vue';
import { initStore, useAccessStore, useTabbarStore } from '@vben-core/stores';
import { initStore } from '@vben-core/stores';
/**
* @zh_CN pinia
@ -13,4 +13,7 @@ async function setupStore(app: App, options: InitStoreOptions) {
app.use(pinia);
}
export { setupStore, useAccessStore, useTabbarStore };
export { setupStore };
export { useAccessStore } from './modules/access';
export { useAppStore } from './modules/app';

View File

@ -0,0 +1,99 @@
import type { MenuRecordRaw, UserInfo } from '@vben/types';
import type { LoginAndRegisterParams } from '@vben/universal-ui';
import type { RouteRecordRaw } from 'vue-router';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { DEFAULT_HOME_PATH } from '@vben/constants';
import { useCoreAccessStore } from '@vben-core/stores';
import { defineStore } from 'pinia';
import { getUserInfo, userLogin } from '#/apis';
export const useAccessStore = defineStore('access', () => {
const coreStoreAccess = useCoreAccessStore();
const router = useRouter();
const loading = ref(false);
const accessToken = computed(() => coreStoreAccess.getAccessToken);
const userRoles = computed(() => coreStoreAccess.getUserRoles);
const userInfo = computed(() => coreStoreAccess.getUserInfo);
const accessRoutes = computed(() => coreStoreAccess.getAccessRoutes);
function setAccessMenus(menus: MenuRecordRaw[]) {
coreStoreAccess.setAccessMenus(menus);
}
function setAccessRoutes(routes: RouteRecordRaw[]) {
coreStoreAccess.setAccessRoutes(routes);
}
/**
*
* Asynchronously handle the login process
* @param params
*/
async function authLogin(
params: LoginAndRegisterParams,
onSuccess?: () => Promise<void>,
) {
// 异步处理用户登录操作并获取 accessToken
let userInfo: UserInfo | null = null;
try {
loading.value = true;
const { accessToken, refreshToken } = await userLogin(params);
// 如果成功获取到 accessToken
// If accessToken is successfully obtained
if (accessToken) {
// 将 accessToken 存储到 accessStore 中
// Store the accessToken in accessStore
coreStoreAccess.setAccessToken(accessToken);
coreStoreAccess.setRefreshToken(refreshToken);
// 获取用户信息并存储到 accessStore 中
// Get user information and store it in accessStore
userInfo = await fetchUserInfo();
coreStoreAccess.setUserInfo(userInfo);
onSuccess
? await onSuccess?.()
: await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
}
} finally {
loading.value = false;
}
return {
accessToken,
userInfo,
};
}
async function fetchUserInfo() {
let userInfo: UserInfo | null = null;
userInfo = await getUserInfo();
coreStoreAccess.setUserInfo(userInfo);
return userInfo;
}
function reset() {
coreStoreAccess.$reset();
}
return {
accessRoutes,
accessToken,
authLogin,
fetchUserInfo,
loading,
reset,
setAccessMenus,
setAccessRoutes,
userInfo,
userRoles,
};
});

View File

@ -0,0 +1,20 @@
import { useCoreAccessStore, useCoreTabbarStore } from '@vben-core/stores';
import { defineStore } from 'pinia';
export const useAppStore = defineStore('app', () => {
const coreStoreAccess = useCoreAccessStore();
const coreTabbarStore = useCoreTabbarStore();
/**
*
*/
async function resetAppState() {
coreStoreAccess.$reset();
coreTabbarStore.$reset();
}
return {
resetAppState,
};
});

View File

@ -1,17 +0,0 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useCounterStore } from './example';
describe('useCounterStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('count test', () => {
setActivePinia(createPinia());
const counterStore = useCounterStore();
expect(counterStore.count).toBe(0);
});
});

View File

@ -1,14 +0,0 @@
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
actions: {
increment() {
this.count++;
},
},
getters: {
double: (state) => state.count * 2,
},
persist: [],
state: () => ({ count: 0 }),
});

View File

@ -1,80 +1,36 @@
<script lang="ts" setup>
import type { LoginAndRegisterParams } from '@vben/universal-ui';
import { computed } from 'vue';
import { useRouter } from 'vue-router';
import { DEFAULT_HOME_PATH } from '@vben/constants';
import { $t } from '@vben/locales';
import { AuthenticationLogin } from '@vben/universal-ui';
import { useRequest } from '@vben-core/request';
import { useAccessStore } from '@vben-core/stores';
import { App } from 'ant-design-vue';
import { getUserInfo, userLogin } from '#/apis';
import { useAccessStore } from '#/store';
defineOptions({ name: 'Login' });
const router = useRouter();
const accessStore = useAccessStore();
const { notification } = App.useApp();
const { loading, runAsync: runUserLogin } = useRequest(userLogin, {
manual: true,
});
const { loading: userInfoLoading, runAsync: runGetUserInfo } = useRequest(
getUserInfo,
{
manual: true,
},
);
/**
* 异步处理登录操作
* Asynchronously handle the login process
* @param values 登录表单数据
* @param params 登录表单数据
*/
async function handleLogin(values: LoginAndRegisterParams) {
// accessToken
// Asynchronously handle the user login operation and obtain the accessToken
const { accessToken, refreshToken } = await runUserLogin(values);
// accessToken
// If accessToken is successfully obtained
if (accessToken) {
// accessToken accessStore
// Store the accessToken in accessStore
accessStore.setAccessToken(accessToken);
accessStore.setRefreshToken(refreshToken);
// accessStore
// Get user information and store it in accessStore
const userInfo = await runGetUserInfo();
accessStore.setUserInfo(userInfo);
// homePath
// Redirect to the homePath defined in the user information
await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
async function handleLogin(params: LoginAndRegisterParams) {
const { userInfo } = await accessStore.authLogin(params);
if (userInfo?.realName) {
notification.success({
description: `${$t('authentication.login-success-desc')}:${userInfo.realName}`,
description: `${$t('authentication.login-success-desc')}:${userInfo?.realName}`,
duration: 3,
message: $t('authentication.login-success'),
});
}
}
const loginLoading = computed(() => {
return loading.value || userInfoLoading.value;
});
</script>
<template>
<AuthenticationLogin
:loading="loginLoading"
:loading="accessStore.loading"
password-placeholder="123456"
username-placeholder="vben"
@submit="handleLogin"

View File

@ -24,7 +24,7 @@ import AnalyticsVisitsSource from '../analytics/analytics-visits-source.vue';
defineOptions({ name: 'Workspace' });
const { userInfo } = useAccessStore();
const accessStore = useAccessStore();
const projectItems: WorkbenchProjectItem[] = [
{
@ -203,10 +203,10 @@ const trendItems: WorkbenchTrendItem[] = [
<template>
<div class="p-5">
<WorkbenchHeader
:avatar="userInfo?.avatar || preferences.app.defaultAvatar"
:avatar="accessStore.userInfo?.avatar || preferences.app.defaultAvatar"
>
<template #title>
早安, {{ userInfo?.realName }}, 开始您一天的工作吧
早安, {{ accessStore.userInfo?.realName }}, 开始您一天的工作吧
</template>
<template #description> 今日晴20 - 32 </template>
</WorkbenchHeader>

View File

@ -0,0 +1,13 @@
<script lang="ts" setup>
import { Fallback } from '@vben/universal-ui';
defineOptions({ name: 'AccessFrontendAccessTest1' });
</script>
<template>
<Fallback
description="当前页面仅 Super 角色可见"
status="comming-soon"
title="页面访问测试"
/>
</template>

View File

@ -1,16 +1,48 @@
<script lang="ts" setup>
import type { LoginAndRegisterParams } from '@vben/universal-ui';
import { useRouter } from 'vue-router';
import { useAccess } from '@vben/access';
import { useAccessStore } from '@vben-core/stores';
import { Button } from 'ant-design-vue';
import { useAccessStore, useAppStore } from '#/store';
defineOptions({ name: 'AccessBackend' });
const { currentAccessMode } = useAccess();
const { accessMode } = useAccess();
const accessStore = useAccessStore();
const appStore = useAppStore();
const router = useRouter();
function roleButtonType(role: string) {
return accessStore.getUserRoles.includes(role) ? 'primary' : 'default';
return accessStore.userRoles.includes(role) ? 'primary' : 'default';
}
async function changeAccount(role: string) {
if (accessStore.userRoles.includes(role)) {
return;
}
const accounts: Record<string, LoginAndRegisterParams> = {
admin: {
password: '123456',
username: 'admin',
},
super: {
password: '123456',
username: 'vben',
},
user: {
password: '123456',
username: 'jack',
},
};
const account = accounts[role];
await appStore.resetAppState();
await accessStore.authLogin(account, async () => {
router.go(0);
});
}
</script>
@ -19,26 +51,39 @@ function roleButtonType(role: string) {
<div class="card-box p-5">
<h1 class="text-xl font-semibold">前端页面访问演示</h1>
<div class="text-foreground/80 mt-2">
由于刷新的时候会请求用户信息接口会根据接口重置角色信息所以刷新后界面会恢复原样如果不需要可以注释对应的代码
切换不同的账号观察左侧菜单变化
</div>
</div>
<template v-if="currentAccessMode === 'frontend'">
<template v-if="accessMode === 'frontend'">
<div class="card-box mt-5 p-5 font-semibold">
当前权限模式:
<span class="text-primary mx-4">{{ currentAccessMode }}</span>
<span class="text-primary mx-4">{{ accessMode }}</span>
<Button type="primary">切换权限模式</Button>
</div>
<div class="card-box mt-5 p-5 font-semibold">
当前用户角色:
<span class="text-primary mx-4">{{ accessStore.getUserRoles }}</span>
<Button :type="roleButtonType('admin')"> 切换为 Admin 角色 </Button>
<Button :type="roleButtonType('user')" class="mx-4">
切换为 User 角色
<div class="mb-3">
当前账号:
<span class="text-primary mx-4">
{{ accessStore.userRoles }}
</span>
</div>
<Button :type="roleButtonType('super')" @click="changeAccount('super')">
切换为 Super 账号
</Button>
<div class="text-foreground/80 mt-2">角色后请查看左侧菜单变化</div>
<Button
:type="roleButtonType('admin')"
class="mx-4"
@click="changeAccount('admin')"
>
切换为 Admin 账号
</Button>
<Button :type="roleButtonType('user')" @click="changeAccount('user')">
切换为 User 账号
</Button>
</div>
</template>
</div>

View File

@ -38,7 +38,7 @@
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-i": "^2.29.1",
"eslint-plugin-jsdoc": "^48.5.0",
"eslint-plugin-jsdoc": "^48.5.2",
"eslint-plugin-jsonc": "^2.16.0",
"eslint-plugin-n": "^17.9.0",
"eslint-plugin-no-only-tests": "^3.1.0",

View File

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

View File

@ -58,7 +58,7 @@ interface AccessState {
/**
* @zh_CN 访
*/
const useAccessStore = defineStore('access', {
const useCoreAccessStore = defineStore('core-access', {
actions: {
setAccessMenus(menus: MenuRecordRaw[]) {
this.accessMenus = menus;
@ -72,7 +72,7 @@ const useAccessStore = defineStore('access', {
setRefreshToken(token: AccessToken) {
this.refreshToken = token;
},
setUserInfo(userInfo: BasicUserInfo) {
setUserInfo(userInfo: BasicUserInfo | null) {
// 设置用户信息
this.userInfo = userInfo;
// 设置角色信息
@ -105,7 +105,7 @@ const useAccessStore = defineStore('access', {
},
persist: {
// 持久化
paths: ['accessToken', 'refreshToken', 'userRoles', 'userInfo'],
paths: ['accessToken', 'refreshToken'],
},
state: (): AccessState => ({
accessMenus: [],
@ -120,7 +120,7 @@ const useAccessStore = defineStore('access', {
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useAccessStore, hot));
hot.accept(acceptHMRUpdate(useCoreAccessStore, hot));
}
export { useAccessStore };
export { useCoreAccessStore };

View File

@ -3,9 +3,9 @@ import { createRouter, createWebHistory } from 'vue-router';
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useTabbarStore } from './tabbar';
import { useCoreTabbarStore } from './tabbar';
describe('useAccessStore', () => {
describe('useCoreAccessStore', () => {
const router = createRouter({
history: createWebHistory(),
routes: [],
@ -18,7 +18,7 @@ describe('useAccessStore', () => {
});
it('adds a new tab', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const tab: any = {
fullPath: '/home',
meta: {},
@ -31,7 +31,7 @@ describe('useAccessStore', () => {
});
it('adds a new tab if it does not exist', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const newTab: any = {
fullPath: '/new',
meta: {},
@ -43,7 +43,7 @@ describe('useAccessStore', () => {
});
it('updates an existing tab instead of adding a new one', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const initialTab: any = {
fullPath: '/existing',
meta: {},
@ -59,7 +59,7 @@ describe('useAccessStore', () => {
});
it('closes all tabs', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
store.tabs = [
{ fullPath: '/home', meta: {}, name: 'Home', path: '/home' },
] as any;
@ -72,7 +72,7 @@ describe('useAccessStore', () => {
});
it('returns all tabs including affix tabs', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
store.tabs = [
{ fullPath: '/home', meta: {}, name: 'Home', path: '/home' },
] as any;
@ -86,7 +86,7 @@ describe('useAccessStore', () => {
});
it('closes a non-affix tab', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const tab: any = {
fullPath: '/closable',
meta: {},
@ -99,7 +99,7 @@ describe('useAccessStore', () => {
});
it('does not close an affix tab', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const affixTab: any = {
fullPath: '/affix',
meta: { affixTab: true },
@ -112,14 +112,14 @@ describe('useAccessStore', () => {
});
it('returns all cache tabs', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
store.cacheTabs.add('Home');
store.cacheTabs.add('About');
expect(store.getCacheTabs).toEqual(['Home', 'About']);
});
it('returns all tabs, including affix tabs', () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const normalTab: any = {
fullPath: '/normal',
meta: {},
@ -139,7 +139,7 @@ describe('useAccessStore', () => {
});
it('navigates to a specific tab', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const tab: any = { meta: {}, name: 'Dashboard', path: '/dashboard' };
await store._goToTab(tab, router);
@ -152,7 +152,7 @@ describe('useAccessStore', () => {
});
it('closes multiple tabs by paths', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@ -179,7 +179,7 @@ describe('useAccessStore', () => {
});
it('closes all tabs to the left of the specified tab', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@ -207,7 +207,7 @@ describe('useAccessStore', () => {
});
it('closes all tabs except the specified tab', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
store.addTab({
fullPath: '/home',
meta: {},
@ -235,7 +235,7 @@ describe('useAccessStore', () => {
});
it('closes all tabs to the right of the specified tab', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const targetTab: any = {
fullPath: '/home',
meta: {},
@ -263,7 +263,7 @@ describe('useAccessStore', () => {
});
it('closes the tab with the specified key', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const keyToClose = '/about';
store.addTab({
fullPath: '/home',
@ -293,7 +293,7 @@ describe('useAccessStore', () => {
});
it('refreshes the current tab', async () => {
const store = useTabbarStore();
const store = useCoreTabbarStore();
const currentTab: any = {
fullPath: '/dashboard',
meta: { name: 'Dashboard' },
@ -302,7 +302,7 @@ describe('useAccessStore', () => {
};
router.currentRoute.value = currentTab;
await store.refreshTab(router);
await store.refresh(router);
expect(store.excludeCacheTabs.has('Dashboard')).toBe(false);
expect(store.renderRouteView).toBe(true);

View File

@ -62,7 +62,7 @@ interface TabsState {
/**
* @zh_CN 访
*/
const useTabbarStore = defineStore('tabbar', {
const useCoreTabbarStore = defineStore('core-tabbar', {
actions: {
/**
* Close tabs in bulk
@ -290,7 +290,7 @@ const useTabbarStore = defineStore('tabbar', {
/**
*
*/
async refreshTab(router: Router) {
async refresh(router: Router) {
const { currentRoute } = router;
const { name } = currentRoute.value;
@ -395,7 +395,7 @@ const useTabbarStore = defineStore('tabbar', {
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useTabbarStore, hot));
hot.accept(acceptHMRUpdate(useCoreTabbarStore, hot));
}
export { useTabbarStore };
export { useCoreTabbarStore };

View File

@ -39,10 +39,12 @@
"@vue/shared": "^3.4.31",
"clsx": "2.1.1",
"defu": "^6.1.4",
"lodash.clonedeep": "^4.5.0",
"nprogress": "^0.2.0",
"tailwind-merge": "^2.3.0"
},
"devDependencies": {
"@types/lodash.clonedeep": "^4.5.9",
"@types/nprogress": "^0.2.3"
}
}

View File

@ -10,3 +10,4 @@ export * from './tree';
export * from './unique';
export * from './update-css-variables';
export * from './window';
export { default as cloneDepp } from 'lodash.clonedeep';

View File

@ -3,6 +3,8 @@ import type { RouteRecordRaw } from 'vue-router';
import type { GeneratorMenuAndRoutesOptions } from '../types';
import { cloneDepp } from '@vben-core/toolkit';
import { generateMenus } from './generate-menus';
import { generateRoutesByBackend } from './generate-routes-backend';
import { generateRoutesByFrontend } from './generate-routes-frontend';
@ -12,6 +14,8 @@ async function generateMenusAndRoutes(
options: GeneratorMenuAndRoutesOptions,
) {
const { router } = options;
options.routes = cloneDepp(options.routes);
// 生成路由
const accessibleRoutes = await generateRoutes(mode, options);

View File

@ -1,4 +1,4 @@
export { default as Authority } from './authority.vue';
export * from './generate-menu-and-routes';
export { default as RoleAuthority } from './role-authority.vue';
export type * from './types';
export * from './use-access';

View File

@ -9,15 +9,15 @@ interface Props {
* - When the permission mode is 'backend', the value can be a code permission value.
* @default ''
*/
value?: string[];
roles?: string[];
}
defineOptions({
name: 'Authority',
name: 'FrontendAuthority',
});
withDefaults(defineProps<Props>(), {
value: undefined,
roles: undefined,
});
</script>

View File

@ -1,28 +1,13 @@
import { computed } from 'vue';
import { preferences } from '@vben-core/preferences';
import { useAccessStore } from '@vben-core/stores';
function useAccess() {
const accessStore = useAccessStore();
const currentAccessMode = computed(() => {
const accessMode = computed(() => {
return preferences.app.accessMode;
});
/**
*
* @param roles
*/
async function changeRoles(roles: string[]): Promise<void> {
if (preferences.app.accessMode !== 'frontend') {
throw new Error(
'The current access mode is not frontend, so the role cannot be changed',
);
}
accessStore.setUserRoles(roles);
}
return { changeRoles, currentAccessMode };
return { accessMode };
}
export { useAccess };

View File

@ -3,14 +3,14 @@ import type { RouteLocationNormalizedLoaded } from 'vue-router';
import { preferences, usePreferences } from '@vben-core/preferences';
import { Spinner } from '@vben-core/shadcn-ui';
import { storeToRefs, useTabbarStore } from '@vben-core/stores';
import { storeToRefs, useCoreTabbarStore } from '@vben-core/stores';
import { IFrameRouterView } from '../../iframe';
import { useContentSpinner } from './use-content-spinner';
defineOptions({ name: 'LayoutContent' });
const tabsStore = useTabbarStore();
const tabsStore = useCoreTabbarStore();
const { keepAlive } = usePreferences();
const { spinning } = useContentSpinner();
@ -64,7 +64,11 @@ function getTransitionName(route: RouteLocationNormalizedLoaded) {
:key="route.fullPath"
/>
</KeepAlive>
<component :is="Component" v-else :key="route.fullPath" />
<component
:is="Component"
v-else-if="renderRouteView"
:key="route.fullPath"
/>
</Transition>
</RouterView>
</div>

View File

@ -2,7 +2,7 @@
import { GlobalSearch, LanguageToggle, ThemeToggle } from '@vben/widgets';
import { usePreferences } from '@vben-core/preferences';
import { VbenFullScreen } from '@vben-core/shadcn-ui';
import { useAccessStore } from '@vben-core/stores';
import { useCoreAccessStore } from '@vben-core/stores';
interface Props {
/**
@ -19,7 +19,7 @@ withDefaults(defineProps<Props>(), {
theme: 'light',
});
const accessStore = useAccessStore();
const accessStore = useCoreAccessStore();
const { globalSearchShortcutKey } = usePreferences();
</script>

View File

@ -5,12 +5,12 @@ import { useRoute } from 'vue-router';
import { findRootMenuByPath } from '@vben-core/helpers';
import { preferences } from '@vben-core/preferences';
import { useAccessStore } from '@vben-core/stores';
import { useCoreAccessStore } from '@vben-core/stores';
import { useNavigation } from './use-navigation';
function useExtraMenu() {
const accessStore = useAccessStore();
const accessStore = useCoreAccessStore();
const { navigation } = useNavigation();
const menus = computed(() => accessStore.getAccessMenus);

View File

@ -5,12 +5,12 @@ import { useRoute } from 'vue-router';
import { findRootMenuByPath } from '@vben-core/helpers';
import { preferences, usePreferences } from '@vben-core/preferences';
import { useAccessStore } from '@vben-core/stores';
import { useCoreAccessStore } from '@vben-core/stores';
import { useNavigation } from './use-navigation';
function useMixedMenu() {
const accessStore = useAccessStore();
const accessStore = useCoreAccessStore();
const { navigation } = useNavigation();
const route = useRoute();
const splitSideMenus = ref<MenuRecordRaw[]>([]);

View File

@ -19,14 +19,18 @@ import {
MdiPin,
MdiPinOff,
} from '@vben-core/iconify';
import { storeToRefs, useAccessStore, useTabbarStore } from '@vben-core/stores';
import {
storeToRefs,
useCoreAccessStore,
useCoreTabbarStore,
} from '@vben-core/stores';
import { filterTree } from '@vben-core/toolkit';
function useTabs() {
const router = useRouter();
const route = useRoute();
const accessStore = useAccessStore();
const tabsStore = useTabbarStore();
const accessStore = useCoreAccessStore();
const tabbarStore = useCoreTabbarStore();
const { accessMenus } = storeToRefs(accessStore);
const currentActive = computed(() => {
@ -35,7 +39,7 @@ function useTabs() {
const { locale } = useI18n();
const currentTabs = ref<RouteLocationNormalizedGeneric[]>();
watch([() => tabsStore.getTabs, () => locale.value], ([tabs, _]) => {
watch([() => tabbarStore.getTabs, () => locale.value], ([tabs, _]) => {
currentTabs.value = tabs.map((item) => wrapperTabLocale(item));
});
@ -46,7 +50,7 @@ function useTabs() {
const affixTabs = filterTree(router.getRoutes(), (route) => {
return !!route.meta?.affixTab;
});
tabsStore.setAffixTabs(affixTabs);
tabbarStore.setAffixTabs(affixTabs);
};
// 点击tab,跳转路由
@ -56,7 +60,7 @@ function useTabs() {
// 关闭tab
const handleClose = async (key: string) => {
await tabsStore.closeTabByKey(key, router);
await tabbarStore.closeTabByKey(key, router);
};
function wrapperTabLocale(tab: RouteLocationNormalizedGeneric) {
@ -80,14 +84,14 @@ function useTabs() {
watch(
() => route.path,
() => {
tabsStore.addTab(route as RouteLocationNormalized);
tabbarStore.addTab(route as RouteLocationNormalized);
},
{ immediate: true },
);
const createContextMenus = (tab: TabItem) => {
const tabs = tabsStore.getTabs;
const affixTabs = tabsStore.affixTabs;
const tabs = tabbarStore.getTabs;
const affixTabs = tabbarStore.affixTabs;
const index = tabs.findIndex((item) => item.path === tab.path);
const disabled = tabs.length <= 1;
@ -109,7 +113,7 @@ function useTabs() {
{
disabled: !isCurrentTab,
handler: async () => {
await tabsStore.refreshTab(router);
await tabbarStore.refresh(router);
},
icon: IcRoundRefresh,
key: 'reload',
@ -118,7 +122,7 @@ function useTabs() {
{
disabled: !!affixTab || disabled,
handler: async () => {
await tabsStore.closeTab(tab, router);
await tabbarStore.closeTab(tab, router);
},
icon: IcRoundClose,
key: 'close',
@ -127,8 +131,8 @@ function useTabs() {
{
handler: async () => {
await (affixTab
? tabsStore.unPushPinTab(tab)
: tabsStore.pushPinTab(tab));
? tabbarStore.unPushPinTab(tab)
: tabbarStore.pushPinTab(tab));
},
icon: affixTab ? MdiPinOff : MdiPin,
key: 'affix',
@ -140,7 +144,7 @@ function useTabs() {
{
disabled: closeLeftDisabled,
handler: async () => {
await tabsStore.closeLeftTabs(tab);
await tabbarStore.closeLeftTabs(tab);
},
icon: MdiFormatHorizontalAlignLeft,
key: 'close-left',
@ -149,7 +153,7 @@ function useTabs() {
{
disabled: closeRightDisabled,
handler: async () => {
await tabsStore.closeRightTabs(tab);
await tabbarStore.closeRightTabs(tab);
},
icon: MdiFormatHorizontalAlignRight,
key: 'close-right',
@ -159,7 +163,7 @@ function useTabs() {
{
disabled: closeOtherDisabled,
handler: async () => {
await tabsStore.closeOtherTabs(tab);
await tabbarStore.closeOtherTabs(tab);
},
icon: MdiArrowExpandHorizontal,
key: 'close-other',
@ -168,7 +172,7 @@ function useTabs() {
{
disabled,
handler: async () => {
await tabsStore.closeAllTabs(router);
await tabbarStore.closeAllTabs(router);
},
icon: IcRoundMultipleStop,
key: 'close-all',
@ -187,7 +191,7 @@ function useTabs() {
*
*/
const handleUnPushPin = async (tab: TabItem) => {
await tabsStore.unPushPinTab(tab);
await tabbarStore.unPushPinTab(tab);
};
return {

View File

@ -6,12 +6,12 @@ import { useRoute } from 'vue-router';
import { preferences } from '@vben-core/preferences';
import { Spinner } from '@vben-core/shadcn-ui';
import { useTabbarStore } from '@vben-core/stores';
import { useCoreTabbarStore } from '@vben-core/stores';
defineOptions({ name: 'IFrameRouterView' });
const spinningList = ref<boolean[]>([]);
const tabsStore = useTabbarStore();
const tabsStore = useCoreTabbarStore();
const route = useRoute();
const enableTabbar = computed(() => preferences.tabbar.enable);

View File

@ -43,6 +43,7 @@
"@vben-core/design": "workspace:*",
"@vben-core/iconify": "workspace:*",
"@vben-core/shadcn-ui": "workspace:*",
"@vben/constants": "workspace:*",
"@vben/locales": "workspace:*",
"@vben/types": "workspace:*",
"@vueuse/integrations": "^10.11.0",

View File

@ -4,6 +4,7 @@ import type { LoginCodeEmits } from './typings';
import { computed, onBeforeUnmount, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { $t } from '@vben/locales';
import { VbenButton, VbenInput, VbenPinInput } from '@vben-core/shadcn-ui';
@ -26,7 +27,7 @@ defineOptions({
const props = withDefaults(defineProps<Props>(), {
loading: false,
loginPath: '/auth/login',
loginPath: LOGIN_PATH,
});
const emit = defineEmits<{

View File

@ -2,6 +2,7 @@
import { computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { $t } from '@vben/locales';
import { VbenButton, VbenInput } from '@vben-core/shadcn-ui';
@ -24,7 +25,7 @@ defineOptions({
const props = withDefaults(defineProps<Props>(), {
loading: false,
loginPath: '/auth/login',
loginPath: LOGIN_PATH,
});
const emit = defineEmits<{

View File

@ -2,6 +2,7 @@
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { $t } from '@vben/locales';
import { VbenButton } from '@vben-core/shadcn-ui';
@ -26,7 +27,7 @@ defineOptions({
const props = withDefaults(defineProps<Props>(), {
loading: false,
loginPath: '/auth/login',
loginPath: LOGIN_PATH,
});
const router = useRouter();

View File

@ -4,6 +4,7 @@ import type { RegisterEmits } from './typings';
import { computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { $t } from '@vben/locales';
import {
VbenButton,
@ -31,7 +32,7 @@ defineOptions({
const props = withDefaults(defineProps<Props>(), {
loading: false,
loginPath: '/auth/login',
loginPath: LOGIN_PATH,
});
const emit = defineEmits<{

View File

@ -9,8 +9,9 @@ page:
page: Page visit
button: Button control
loading-menu: In the loading menu
access-test-1: Access test page 1
access-test-2: Access test page 2
access-test-1: Admin visit
access-test-2: User visit
access-test-3: Super visit
nested:
title: Nested Menu
menu1: Menu 1

View File

@ -8,8 +8,9 @@ page:
backend-control: 后端控制
page: 页面访问
button: 按钮控制
access-test-1: 权限测试页1
access-test-2: 权限测试页2
access-test-1: Admin 角色可见
access-test-2: User 角色可见
access-test-3: Super 角色可见
nested:
title: 嵌套菜单

37
pnpm-lock.yaml generated
View File

@ -293,8 +293,8 @@ importers:
specifier: ^2.29.1
version: 2.29.1(@typescript-eslint/parser@7.15.0(eslint@8.57.0)(typescript@5.5.3))(eslint@8.57.0)
eslint-plugin-jsdoc:
specifier: ^48.5.0
version: 48.5.0(eslint@8.57.0)
specifier: ^48.5.2
version: 48.5.2(eslint@8.57.0)
eslint-plugin-jsonc:
specifier: ^2.16.0
version: 2.16.0(eslint@8.57.0)
@ -666,6 +666,9 @@ importers:
defu:
specifier: ^6.1.4
version: 6.1.4
lodash.clonedeep:
specifier: ^4.5.0
version: 4.5.0
nprogress:
specifier: ^0.2.0
version: 0.2.0
@ -673,6 +676,9 @@ importers:
specifier: ^2.3.0
version: 2.3.0
devDependencies:
'@types/lodash.clonedeep':
specifier: ^4.5.9
version: 4.5.9
'@types/nprogress':
specifier: ^0.2.3
version: 0.2.3
@ -888,6 +894,9 @@ importers:
'@vben-core/shadcn-ui':
specifier: workspace:*
version: link:../../@core/ui-kit/shadcn-ui
'@vben/constants':
specifier: workspace:*
version: link:../../constants
'@vben/locales':
specifier: workspace:*
version: link:../../locales
@ -3051,7 +3060,6 @@ 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
@ -3559,6 +3567,12 @@ packages:
'@types/linkify-it@5.0.0':
resolution: {integrity: sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==}
'@types/lodash.clonedeep@4.5.9':
resolution: {integrity: sha512-19429mWC+FyaAhOLzsS8kZUsI+/GmBAQ0HFiCPsKGU+7pBXOQWhyrY6xNNDwUSX8SMZMJvuFVMF9O5dQOlQK9Q==}
'@types/lodash@4.17.6':
resolution: {integrity: sha512-OpXEVoCKSS3lQqjx9GGGOapBeuW5eUboYHRlHP9urXPX25IKZ6AnP5ZRxtVf63iieUbsHxLn8NQ5Nlftc6yzAA==}
'@types/markdown-it@14.1.1':
resolution: {integrity: sha512-4NpsnpYl2Gt1ljyBGrKMxFYAYvpqbnnkgP/i/g+NLpjEUa3obn1XJCur9YbEXKDAkaXqsR1LbDnGEJ0MmKFxfg==}
@ -5226,8 +5240,8 @@ packages:
peerDependencies:
eslint: ^7.2.0 || ^8
eslint-plugin-jsdoc@48.5.0:
resolution: {integrity: sha512-ukXPNpGby3KjCveCizIS8t1EbuJEHYEu/tBg8GCbn/YbHcXwphyvYCdvRZ/oMRfTscGSSzfsWoZ+ZkAP0/6YMQ==}
eslint-plugin-jsdoc@48.5.2:
resolution: {integrity: sha512-VXBJFviQz30rynlOEQ+dNWLmeopjoAgutUVrWOZwm6Ki4EVDm4XkyIqAV/Zhf7FcDr0AG0aGmRn5FxxCtAF0tA==}
engines: {node: '>=18'}
peerDependencies:
eslint: ^7.0.0 || ^8.0.0 || ^9.0.0
@ -6436,6 +6450,9 @@ packages:
lodash.castarray@4.4.0:
resolution: {integrity: sha512-aVx8ztPv7/2ULbArGJ2Y42bG1mEQ5mGjpdvrbJcJFU3TbYybe+QlLS4pst9zV52ymy2in1KpFPiZnAOATxD4+Q==}
lodash.clonedeep@4.5.0:
resolution: {integrity: sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==}
lodash.debounce@4.0.8:
resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}
@ -12265,6 +12282,12 @@ snapshots:
'@types/linkify-it@5.0.0': {}
'@types/lodash.clonedeep@4.5.9':
dependencies:
'@types/lodash': 4.17.6
'@types/lodash@4.17.6': {}
'@types/markdown-it@14.1.1':
dependencies:
'@types/linkify-it': 5.0.0
@ -14271,7 +14294,7 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
eslint-plugin-jsdoc@48.5.0(eslint@8.57.0):
eslint-plugin-jsdoc@48.5.2(eslint@8.57.0):
dependencies:
'@es-joy/jsdoccomment': 0.43.1
are-docs-informative: 0.0.2
@ -15647,6 +15670,8 @@ snapshots:
lodash.castarray@4.4.0: {}
lodash.clonedeep@4.5.0: {}
lodash.debounce@4.0.8: {}
lodash.get@4.4.2: {}