mirror of
https://github.com/vbenjs/vue-vben-admin.git
synced 2025-08-26 16:46:19 +08:00
perf: Improve the use of store in the app
This commit is contained in:
@@ -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}`,
|
||||
|
@@ -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() {
|
||||
|
@@ -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({
|
||||
|
@@ -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'),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
@@ -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';
|
||||
|
99
apps/web-antd/src/store/modules/access.ts
Normal file
99
apps/web-antd/src/store/modules/access.ts
Normal 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,
|
||||
};
|
||||
});
|
20
apps/web-antd/src/store/modules/app.ts
Normal file
20
apps/web-antd/src/store/modules/app.ts
Normal 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,
|
||||
};
|
||||
});
|
@@ -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);
|
||||
});
|
||||
});
|
@@ -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 }),
|
||||
});
|
@@ -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"
|
||||
|
@@ -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>
|
||||
|
@@ -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>
|
@@ -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>
|
||||
|
Reference in New Issue
Block a user