Merge remote-tracking branch 'yudao/dev' into dev

pull/108/head
jason 2025-05-19 12:39:10 +08:00
commit 4469e9dfc7
30 changed files with 394 additions and 291 deletions

View File

@ -1,2 +1,4 @@
export { default as TableAction } from './table-action.vue';
export const ACTION_KEY = 'action_key_msg';
export * from './typing';

View File

@ -69,7 +69,6 @@ const getActions = computed(() => {
.map((action) => {
const { popConfirm } = action;
return {
// getPopupContainer: document.body,
type: 'link' as ButtonType,
...action,
...popConfirm,
@ -135,7 +134,7 @@ function handleMenuClick(e: any) {
</script>
<template>
<div class="m-table-action">
<div class="table-actions">
<Space
:size="
getActions?.some((item: ActionItem) => item.type === 'link') ? 0 : 8
@ -230,7 +229,7 @@ function handleMenuClick(e: any) {
</div>
</template>
<style lang="scss">
.m-table-action {
.table-actions {
.ant-btn {
padding: 4px;
margin-left: 0;

View File

@ -1,16 +1,10 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemDictDataApi } from '#/api/system/dict/data';
import type { SystemDictTypeApi } from '#/api/system/dict/type';
import { useAccess } from '@vben/access';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { z } from '#/adapter/form';
import { getSimpleDictTypeList } from '#/api/system/dict/type';
import { CommonStatusEnum, DICT_TYPE, getDictOptions } from '#/utils';
const { hasAccessByCodes } = useAccess();
// ============================== 字典类型 ==============================
/** 类型新增/修改的表单 */
@ -96,9 +90,7 @@ export function useTypeGridFormSchema(): VbenFormSchema[] {
}
/** 类型列表的字段 */
export function useTypeGridColumns<T = SystemDictTypeApi.DictType>(
onActionClick: OnActionClickFn<T>,
): VxeTableGridOptions['columns'] {
export function useTypeGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
@ -136,29 +128,10 @@ export function useTypeGridColumns<T = SystemDictTypeApi.DictType>(
formatter: 'formatDateTime',
},
{
minWidth: 120,
title: '操作',
field: 'operation',
width: 160,
fixed: 'right',
align: 'center',
cellRender: {
attrs: {
nameField: 'type',
nameTitle: '字典类型',
onClick: onActionClick,
},
name: 'CellOperation',
options: [
{
code: 'edit',
show: hasAccessByCodes(['system:dict:update']),
},
{
code: 'delete',
show: hasAccessByCodes(['system:dict:delete']),
},
],
},
slots: { default: 'actions' },
},
];
}
@ -310,9 +283,7 @@ export function useDataGridFormSchema(): VbenFormSchema[] {
/**
*
*/
export function useDataGridColumns<T = SystemDictDataApi.DictData>(
onActionClick: OnActionClickFn<T>,
): VxeTableGridOptions['columns'] {
export function useDataGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
@ -360,29 +331,10 @@ export function useDataGridColumns<T = SystemDictDataApi.DictData>(
formatter: 'formatDateTime',
},
{
minWidth: 120,
title: '操作',
field: 'operation',
width: 160,
fixed: 'right',
align: 'center',
cellRender: {
attrs: {
nameField: 'label',
nameTitle: '字典数据',
onClick: onActionClick,
},
name: 'CellOperation',
options: [
{
code: 'edit',
show: hasAccessByCodes(['system:dict:update']),
},
{
code: 'delete',
show: hasAccessByCodes(['system:dict:delete']),
},
],
},
slots: { default: 'actions' },
},
];
}

View File

@ -1,8 +1,5 @@
<script lang="ts" setup>
import type {
OnActionClickParams,
VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemDictDataApi } from '#/api/system/dict/data';
import { watch } from 'vue';
@ -19,6 +16,7 @@ import {
exportDictData,
getDictDataPage,
} from '#/api/system/dict/data';
import { ACTION_KEY, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { useDataGridColumns, useDataGridFormSchema } from '../data';
@ -53,41 +51,22 @@ function onCreate() {
}
/** 编辑字典数据 */
function onEdit(row: any) {
function onEdit(row: SystemDictDataApi.DictData) {
dataFormModalApi.setData(row).open();
}
/** 删除字典数据 */
async function onDelete(row: any) {
const hideLoading = message.loading({
content: $t('common.processing'),
duration: 0,
key: 'process_message',
async function onDelete(row: SystemDictDataApi.DictData) {
message.loading({
content: $t('ui.actionMessage.deleting', [row.label]),
key: ACTION_KEY,
});
try {
await deleteDictData(row.id);
message.success({
content: $t('common.operationSuccess'),
key: 'process_message',
});
onRefresh();
} finally {
hideLoading();
}
}
/** 表格操作按钮回调 */
function onActionClick({ code, row }: OnActionClickParams) {
switch (code) {
case 'delete': {
onDelete(row);
break;
}
case 'edit': {
onEdit(row);
break;
}
}
await deleteDictData(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.label]),
key: ACTION_KEY,
});
onRefresh();
}
const [Grid, gridApi] = useVbenVxeGrid({
@ -95,7 +74,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
schema: useDataGridFormSchema(),
},
gridOptions: {
columns: useDataGridColumns(onActionClick),
columns: useDataGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
@ -155,6 +134,30 @@ watch(
{{ $t('ui.actionTitle.export') }}
</Button>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'link',
icon: 'ant-design:edit-outlined',
auth: ['system:dict:update'],
onClick: onEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'link',
danger: true,
icon: 'ant-design:delete-outlined',
auth: ['system:dict:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.label]),
confirm: onDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</div>
</template>

View File

@ -1,6 +1,5 @@
<script lang="ts" setup>
import type {
OnActionClickParams,
VxeGridListeners,
VxeTableGridOptions,
} from '#/adapter/vxe-table';
@ -18,6 +17,7 @@ import {
exportDictType,
getDictTypePage,
} from '#/api/system/dict/type';
import { ACTION_KEY, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { useTypeGridColumns, useTypeGridFormSchema } from '../data';
@ -53,38 +53,16 @@ function onEdit(row: any) {
/** 删除字典类型 */
async function onDelete(row: SystemDictTypeApi.DictType) {
const hideLoading = message.loading({
content: $t('common.processing'),
duration: 0,
key: 'process_message',
message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
key: ACTION_KEY,
});
try {
await deleteDictType(row.id as number);
message.success({
content: $t('common.operationSuccess'),
key: 'process_message',
});
onRefresh();
} finally {
hideLoading();
}
}
/** 表格操作按钮回调 */
function onActionClick({
code,
row,
}: OnActionClickParams<SystemDictTypeApi.DictType>) {
switch (code) {
case 'delete': {
onDelete(row);
break;
}
case 'edit': {
onEdit(row);
break;
}
}
await deleteDictType(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
key: ACTION_KEY,
});
onRefresh();
}
/** 表格事件 */
@ -99,7 +77,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
schema: useTypeGridFormSchema(),
},
gridOptions: {
columns: useTypeGridColumns(onActionClick),
columns: useTypeGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
@ -150,6 +128,30 @@ const [Grid, gridApi] = useVbenVxeGrid({
{{ $t('ui.actionTitle.export') }}
</Button>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'link',
icon: 'ant-design:edit-outlined',
auth: ['system:dict:update'],
onClick: onEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'link',
danger: true,
icon: 'ant-design:delete-outlined',
auth: ['system:dict:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: onDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</div>
</template>

View File

@ -11,7 +11,7 @@ import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRole, exportRole, getRolePage } from '#/api/system/role';
import { DocAlert } from '#/components/doc-alert';
import { TableAction } from '#/components/table-action';
import { ACTION_KEY, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
@ -58,19 +58,16 @@ function onCreate() {
/** 删除角色 */
async function onDelete(row: SystemRoleApi.Role) {
const hideLoading = message.loading({
message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
key: 'action_process_msg',
key: ACTION_KEY,
});
try {
await deleteRole(row.id as number);
hideLoading();
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
onRefresh();
} catch {
hideLoading();
}
await deleteRole(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
key: ACTION_KEY,
});
onRefresh();
}
/** 分配角色的数据权限 */

View File

@ -15,6 +15,7 @@ import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteTenant, exportTenant, getTenantPage } from '#/api/system/tenant';
import { getTenantPackageList } from '#/api/system/tenant-package';
import { DocAlert } from '#/components/doc-alert';
import { ACTION_KEY, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
@ -58,18 +59,16 @@ function onEdit(row: SystemTenantApi.Tenant) {
/** 删除租户 */
async function onDelete(row: SystemTenantApi.Tenant) {
const hideLoading = message.loading({
message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
key: 'action_process_msg',
key: ACTION_KEY,
});
try {
await deleteTenant(row.id as number);
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
onRefresh();
} catch {
hideLoading();
}
await deleteTenant(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
key: ACTION_KEY,
});
onRefresh();
}
const [Grid, gridApi] = useVbenVxeGrid({
@ -78,8 +77,6 @@ const [Grid, gridApi] = useVbenVxeGrid({
},
gridOptions: {
columns: useGridColumns(getPackageName),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {

View File

@ -13,6 +13,7 @@ import {
getTenantPackagePage,
} from '#/api/system/tenant-package';
import { DocAlert } from '#/components/doc-alert';
import { ACTION_KEY, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
@ -40,18 +41,16 @@ function onEdit(row: SystemTenantPackageApi.TenantPackage) {
/** 删除租户套餐 */
async function onDelete(row: SystemTenantPackageApi.TenantPackage) {
const hideLoading = message.loading({
message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
key: 'action_process_msg',
key: ACTION_KEY,
});
try {
await deleteTenantPackage(row.id as number);
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
onRefresh();
} catch {
hideLoading();
}
await deleteTenantPackage(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
key: ACTION_KEY,
});
onRefresh();
}
const [Grid, gridApi] = useVbenVxeGrid({

View File

@ -19,7 +19,7 @@ import {
updateUserStatus,
} from '#/api/system/user';
import { DocAlert } from '#/components/doc-alert';
import { TableAction } from '#/components/table-action';
import { ACTION_KEY, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { DICT_TYPE, getDictLabel } from '#/utils';
@ -85,18 +85,16 @@ function onEdit(row: SystemUserApi.User) {
/** 删除用户 */
async function onDelete(row: SystemUserApi.User) {
const hideLoading = message.loading({
message.loading({
content: $t('ui.actionMessage.deleting', [row.username]),
duration: 0,
key: 'action_process_msg',
key: ACTION_KEY,
});
try {
await deleteUser(row.id as number);
message.success($t('ui.actionMessage.deleteSuccess', [row.username]));
onRefresh();
} catch {
hideLoading();
}
await deleteUser(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.username]),
key: ACTION_KEY,
});
onRefresh();
}
/** 重置密码 */

View File

@ -339,6 +339,10 @@ interface RouteMeta {
| 'success'
| 'warning'
| string;
/**
* 路由的完整路径作为key默认true
*/
fullPathKey?: boolean;
/**
* 当前路由的子级在菜单中不展现
* @default false
@ -502,6 +506,13 @@ interface RouteMeta {
用于配置页面的徽标颜色。
### fullPathKey
- 类型:`boolean`
- 默认值:`true`
是否将路由的完整路径作为tab key默认true
### activePath
- 类型:`string`
@ -602,3 +613,32 @@ const { refresh } = useRefresh();
refresh();
</script>
```
## 标签页与路由控制
在某些场景下需要单个路由打开多个标签页或者修改路由的query不打开新的标签页
每个标签页Tab使用唯一的key标识设置Tab key有三种方式优先级由高到低
- 使用路由query参数pageKey
```vue
<script setup lang="ts">
import { useRouter } from 'vue-router';
// 跳转路由
const router = useRouter();
router.push({
path: 'path',
query: {
pageKey: 'key',
},
});
```
- 路由的完整路径作为key
`meta` 属性中的 `fullPathKey`不为false则使用路由`fullPath`作为key
- 路由的path作为key
`meta` 属性中的 `fullPathKey`为false则使用路由`path`作为key

View File

@ -12,7 +12,7 @@
"license": "MIT",
"type": "module",
"scripts": {
"stub": "pnpm unbuild"
"stub": "pnpm unbuild --stub"
},
"files": [
"dist"

View File

@ -1,3 +1,8 @@
import type { RouteLocationNormalized } from 'vue-router';
export type TabDefinition = RouteLocationNormalized;
export interface TabDefinition extends RouteLocationNormalized {
/**
* key
*/
key?: string;
}

View File

@ -43,6 +43,10 @@ interface RouteMeta {
| 'success'
| 'warning'
| string;
/**
* keytrue
*/
fullPathKey?: boolean;
/**
*
* @default false

View File

@ -36,7 +36,7 @@ export interface VbenButtonGroupProps
btnClass?: any;
gap?: number;
multiple?: boolean;
options?: { label: CustomRenderType; value: ValueType }[];
options?: { [key: string]: any; label: CustomRenderType; value: ValueType }[];
showIcon?: boolean;
size?: 'large' | 'middle' | 'small';
}

View File

@ -119,7 +119,7 @@ async function onBtnClick(value: ValueType) {
<CircleCheckBig v-else-if="innerValue.includes(btn.value)" />
<Circle v-else />
</div>
<slot name="option" :label="btn.label" :value="btn.value">
<slot name="option" :label="btn.label" :value="btn.value" :data="btn">
<VbenRenderContent :content="btn.label" />
</slot>
</Button>
@ -127,6 +127,9 @@ async function onBtnClick(value: ValueType) {
</template>
<style lang="scss" scoped>
.vben-check-button-group {
display: flex;
flex-wrap: wrap;
&:deep(.size-large) button {
.icon-wrapper {
margin-right: 0.3rem;
@ -159,5 +162,16 @@ async function onBtnClick(value: ValueType) {
}
}
}
&.no-gap > :deep(button):nth-of-type(1) {
border-right-width: 0;
}
&.no-gap {
:deep(button + button) {
margin-right: -1px;
border-left-width: 1px;
}
}
}
</style>

View File

@ -224,15 +224,20 @@ defineExpose({
:class="
cn('cursor-pointer', getNodeClass?.(item), {
'data-[selected]:bg-accent': !multiple,
'cursor-not-allowed': disabled,
})
"
v-bind="
Object.assign(item.bind, {
onfocus: disabled ? 'this.blur()' : undefined,
})
"
v-bind="item.bind"
@select="
(event) => {
if (event.detail.originalEvent.type === 'click') {
event.preventDefault();
}
onSelect(item, event.detail.isSelected);
!disabled && onSelect(item, event.detail.isSelected);
}
"
@toggle="
@ -240,7 +245,7 @@ defineExpose({
if (event.detail.originalEvent.type === 'click') {
event.preventDefault();
}
onToggle(item);
!disabled && onToggle(item);
}
"
class="tree-node focus:ring-grass8 my-0.5 flex items-center rounded px-2 py-1 outline-none focus:ring-2"
@ -262,10 +267,11 @@ defineExpose({
<Checkbox
v-if="multiple"
:checked="isSelected"
:disabled="disabled"
:indeterminate="isIndeterminate"
@click="
() => {
handleSelect();
!disabled && handleSelect();
// onSelect(item, !isSelected);
}
"
@ -276,7 +282,7 @@ defineExpose({
(_event) => {
// $event.stopPropagation();
// $event.preventDefault();
handleSelect();
!disabled && handleSelect();
// onSelect(item, !isSelected);
}
"

View File

@ -40,14 +40,14 @@ const style = computed(() => {
const tabsView = computed(() => {
return props.tabs.map((tab) => {
const { fullPath, meta, name, path } = tab || {};
const { fullPath, meta, name, path, key } = tab || {};
const { affixTab, icon, newTabTitle, tabClosable, title } = meta || {};
return {
affixTab: !!affixTab,
closable: Reflect.has(meta, 'tabClosable') ? !!tabClosable : true,
fullPath,
icon: icon as string,
key: fullPath || path,
key,
meta,
name,
path,

View File

@ -47,14 +47,14 @@ const typeWithClass = computed(() => {
const tabsView = computed(() => {
return props.tabs.map((tab) => {
const { fullPath, meta, name, path } = tab || {};
const { fullPath, meta, name, path, key } = tab || {};
const { affixTab, icon, newTabTitle, tabClosable, title } = meta || {};
return {
affixTab: !!affixTab,
closable: Reflect.has(meta, 'tabClosable') ? !!tabClosable : true,
fullPath,
icon: icon as string,
key: fullPath || path,
key,
meta,
name,
path,

View File

@ -1,3 +1,4 @@
import type { ComputedRef } from 'vue';
import type { RouteLocationNormalized } from 'vue-router';
import { useRoute, useRouter } from 'vue-router';
@ -53,7 +54,24 @@ export function useTabs() {
await tabbarStore.closeTabByKey(key, router);
}
async function setTabTitle(title: string) {
/**
*
*
* @description
* @description ,
*
* @param title -
* - :
* - : ComputedRef
*
* @example
* // 静态标题
* setTabTitle('标签页')
*
* // 动态标题(多语言)
* setTabTitle(computed(() => t('page.title')))
*/
async function setTabTitle(title: ComputedRef<string> | string) {
tabbarStore.setUpdateTime();
await tabbarStore.setTabTitle(route, title);
}

View File

@ -38,7 +38,7 @@ const { authPanelCenter, authPanelLeft, authPanelRight, isDark } =
<template>
<div
:class="[isDark]"
:class="[isDark ? 'dark' : '']"
class="flex min-h-full flex-1 select-none overflow-x-hidden"
>
<template v-if="toolbar">

View File

@ -1 +1,2 @@
export { default as AuthPageLayout } from './authentication.vue';
export * from './types';

View File

@ -9,7 +9,7 @@ import { computed } from 'vue';
import { RouterView } from 'vue-router';
import { preferences, usePreferences } from '@vben/preferences';
import { storeToRefs, useTabbarStore } from '@vben/stores';
import { getTabKey, storeToRefs, useTabbarStore } from '@vben/stores';
import { IFrameRouterView } from '../../iframe';
@ -115,13 +115,13 @@ function transformComponent(
:is="transformComponent(Component, route)"
v-if="renderRouteView"
v-show="!route.meta.iframeSrc"
:key="route.fullPath"
:key="getTabKey(route)"
/>
</KeepAlive>
<component
:is="Component"
v-else-if="renderRouteView"
:key="route.fullPath"
:key="getTabKey(route)"
/>
</Transition>
<template v-else>
@ -134,13 +134,13 @@ function transformComponent(
:is="transformComponent(Component, route)"
v-if="renderRouteView"
v-show="!route.meta.iframeSrc"
:key="route.fullPath"
:key="getTabKey(route)"
/>
</KeepAlive>
<component
:is="Component"
v-else-if="renderRouteView"
:key="route.fullPath"
:key="getTabKey(route)"
/>
</template>
</RouterView>

View File

@ -140,7 +140,10 @@ function useMixedMenu() {
watch(
() => route.path,
(path) => {
const currentPath = (route?.meta?.activePath as string) ?? path;
const currentPath = route?.meta?.activePath ?? route?.meta?.link ?? path;
if (willOpenedByWindow(currentPath)) {
return;
}
calcSideMenus(currentPath);
if (rootMenuPath.value)
defaultSubMap.set(rootMenuPath.value, currentPath);

View File

@ -30,7 +30,7 @@ const {
} = useTabbar();
const menus = computed(() => {
const tab = tabbarStore.getTabByPath(currentActive.value);
const tab = tabbarStore.getTabByKey(currentActive.value);
const menus = createContextMenus(tab);
return menus.map((item) => {
return {

View File

@ -22,7 +22,7 @@ import {
X,
} from '@vben/icons';
import { $t, useI18n } from '@vben/locales';
import { useAccessStore, useTabbarStore } from '@vben/stores';
import { getTabKey, useAccessStore, useTabbarStore } from '@vben/stores';
import { filterTree } from '@vben/utils';
export function useTabbar() {
@ -44,8 +44,11 @@ export function useTabbar() {
toggleTabPin,
} = useTabs();
/**
* tabkey
*/
const currentActive = computed(() => {
return route.fullPath;
return getTabKey(route);
});
const { locale } = useI18n();
@ -73,7 +76,8 @@ export function useTabbar() {
// 点击tab,跳转路由
const handleClick = (key: string) => {
router.push(key);
const { fullPath, path } = tabbarStore.getTabByKey(key);
router.push(fullPath || path);
};
// 关闭tab
@ -100,7 +104,7 @@ export function useTabbar() {
);
watch(
() => route.path,
() => route.fullPath,
() => {
const meta = route.matched?.[route.matched.length - 1]?.meta;
tabbarStore.addTab({

View File

@ -25,6 +25,7 @@
"deleteConfirm": "Are you sure to delete {0}?",
"deleting": "Deleting {0} ...",
"deleteSuccess": "{0} deleted successfully",
"deleteFailed": "{0} deleted failed",
"operationSuccess": "Operation succeeded",
"operationFailed": "Operation failed",
"importSuccess": "Import succeeded",

View File

@ -25,6 +25,7 @@
"deleteConfirm": "确定删除 {0} 吗?",
"deleting": "正在删除 {0} ...",
"deleteSuccess": "{0} 删除成功",
"deleteFailed": "{0} 删除失败",
"operationSuccess": "操作成功",
"operationFailed": "操作失败",
"importSuccess": "导入成功",

View File

@ -22,12 +22,13 @@ describe('useAccessStore', () => {
const tab: any = {
fullPath: '/home',
meta: {},
key: '/home',
name: 'Home',
path: '/home',
};
store.addTab(tab);
const addNewTab = store.addTab(tab);
expect(store.tabs.length).toBe(1);
expect(store.tabs[0]).toEqual(tab);
expect(store.tabs[0]).toEqual(addNewTab);
});
it('adds a new tab if it does not exist', () => {
@ -38,20 +39,22 @@ describe('useAccessStore', () => {
name: 'New',
path: '/new',
};
store.addTab(newTab);
expect(store.tabs).toContainEqual(newTab);
const addNewTab = store.addTab(newTab);
expect(store.tabs).toContainEqual(addNewTab);
});
it('updates an existing tab instead of adding a new one', () => {
const store = useTabbarStore();
const initialTab: any = {
fullPath: '/existing',
meta: {},
meta: {
fullPathKey: false,
},
name: 'Existing',
path: '/existing',
query: {},
};
store.tabs.push(initialTab);
store.addTab(initialTab);
const updatedTab = { ...initialTab, query: { id: '1' } };
store.addTab(updatedTab);
expect(store.tabs.length).toBe(1);
@ -60,9 +63,12 @@ describe('useAccessStore', () => {
it('closes all tabs', async () => {
const store = useTabbarStore();
store.tabs = [
{ fullPath: '/home', meta: {}, name: 'Home', path: '/home' },
] as any;
store.addTab({
fullPath: '/home',
meta: {},
name: 'Home',
path: '/home',
} as any);
router.replace = vi.fn();
await store.closeAllTabs(router);
@ -157,7 +163,7 @@ describe('useAccessStore', () => {
path: '/contact',
} as any);
await store._bulkCloseByPaths(['/home', '/contact']);
await store._bulkCloseByKeys(['/home', '/contact']);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('About');
@ -183,9 +189,8 @@ describe('useAccessStore', () => {
name: 'Contact',
path: '/contact',
};
store.addTab(targetTab);
await store.closeLeftTabs(targetTab);
const addTargetTab = store.addTab(targetTab);
await store.closeLeftTabs(addTargetTab);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('Contact');
@ -205,7 +210,7 @@ describe('useAccessStore', () => {
name: 'About',
path: '/about',
};
store.addTab(targetTab);
const addTargetTab = store.addTab(targetTab);
store.addTab({
fullPath: '/contact',
meta: {},
@ -213,7 +218,7 @@ describe('useAccessStore', () => {
path: '/contact',
} as any);
await store.closeOtherTabs(targetTab);
await store.closeOtherTabs(addTargetTab);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('About');
@ -227,7 +232,7 @@ describe('useAccessStore', () => {
name: 'Home',
path: '/home',
};
store.addTab(targetTab);
const addTargetTab = store.addTab(targetTab);
store.addTab({
fullPath: '/about',
meta: {},
@ -241,7 +246,7 @@ describe('useAccessStore', () => {
path: '/contact',
} as any);
await store.closeRightTabs(targetTab);
await store.closeRightTabs(addTargetTab);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('Home');

View File

@ -1,4 +1,9 @@
import type { Router, RouteRecordNormalized } from 'vue-router';
import type { ComputedRef } from 'vue';
import type {
RouteLocationNormalized,
Router,
RouteRecordNormalized,
} from 'vue-router';
import type { TabDefinition } from '@vben-core/typings';
@ -52,23 +57,23 @@ export const useTabbarStore = defineStore('core-tabbar', {
/**
* Close tabs in bulk
*/
async _bulkCloseByPaths(paths: string[]) {
this.tabs = this.tabs.filter((item) => {
return !paths.includes(getTabPath(item));
});
async _bulkCloseByKeys(keys: string[]) {
const keySet = new Set(keys);
this.tabs = this.tabs.filter(
(item) => !keySet.has(getTabKeyFromTab(item)),
);
this.updateCacheTabs();
await this.updateCacheTabs();
},
/**
* @zh_CN
* @param tab
*/
_close(tab: TabDefinition) {
const { fullPath } = tab;
if (isAffixTab(tab)) {
return;
}
const index = this.tabs.findIndex((item) => item.fullPath === fullPath);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
index !== -1 && this.tabs.splice(index, 1);
},
/**
@ -101,14 +106,17 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @zh_CN
* @param routeTab
*/
addTab(routeTab: TabDefinition) {
const tab = cloneTab(routeTab);
addTab(routeTab: TabDefinition): TabDefinition {
let tab = cloneTab(routeTab);
if (!tab.key) {
tab.key = getTabKey(routeTab);
}
if (!isTabShown(tab)) {
return;
return tab;
}
const tabIndex = this.tabs.findIndex((tab) => {
return getTabPath(tab) === getTabPath(routeTab);
const tabIndex = this.tabs.findIndex((item) => {
return equalTab(item, tab);
});
if (tabIndex === -1) {
@ -154,10 +162,11 @@ export const useTabbarStore = defineStore('core-tabbar', {
mergedTab.meta.newTabTitle = curMeta.newTabTitle;
}
}
tab = mergedTab;
this.tabs.splice(tabIndex, 1, mergedTab);
}
this.updateCacheTabs();
return tab;
},
/**
* @zh_CN
@ -173,65 +182,63 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @param tab
*/
async closeLeftTabs(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index < 1) {
return;
}
const leftTabs = this.tabs.slice(0, index);
const paths: string[] = [];
const keys: string[] = [];
for (const item of leftTabs) {
if (!isAffixTab(item)) {
paths.push(getTabPath(item));
keys.push(item.key as string);
}
}
await this._bulkCloseByPaths(paths);
await this._bulkCloseByKeys(keys);
},
/**
* @zh_CN
* @param tab
*/
async closeOtherTabs(tab: TabDefinition) {
const closePaths = this.tabs.map((item) => getTabPath(item));
const closeKeys = this.tabs.map((item) => getTabKeyFromTab(item));
const paths: string[] = [];
const keys: string[] = [];
for (const path of closePaths) {
if (path !== tab.fullPath) {
const closeTab = this.tabs.find((item) => getTabPath(item) === path);
for (const key of closeKeys) {
if (key !== tab.key) {
const closeTab = this.tabs.find(
(item) => getTabKeyFromTab(item) === key,
);
if (!closeTab) {
continue;
}
if (!isAffixTab(closeTab)) {
paths.push(getTabPath(closeTab));
keys.push(closeTab.key as string);
}
}
}
await this._bulkCloseByPaths(paths);
await this._bulkCloseByKeys(keys);
},
/**
* @zh_CN
* @param tab
*/
async closeRightTabs(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index !== -1 && index < this.tabs.length - 1) {
const rightTabs = this.tabs.slice(index + 1);
const paths: string[] = [];
const keys: string[] = [];
for (const item of rightTabs) {
if (!isAffixTab(item)) {
paths.push(getTabPath(item));
keys.push(item.key as string);
}
}
await this._bulkCloseByPaths(paths);
await this._bulkCloseByKeys(keys);
}
},
@ -242,15 +249,14 @@ export const useTabbarStore = defineStore('core-tabbar', {
*/
async closeTab(tab: TabDefinition, router: Router) {
const { currentRoute } = router;
// 关闭不是激活选项卡
if (getTabPath(currentRoute.value) !== getTabPath(tab)) {
if (getTabKey(currentRoute.value) !== getTabKeyFromTab(tab)) {
this._close(tab);
this.updateCacheTabs();
return;
}
const index = this.getTabs.findIndex(
(item) => getTabPath(item) === getTabPath(currentRoute.value),
(item) => getTabKeyFromTab(item) === getTabKey(currentRoute.value),
);
const before = this.getTabs[index - 1];
@ -277,7 +283,7 @@ export const useTabbarStore = defineStore('core-tabbar', {
async closeTabByKey(key: string, router: Router) {
const originKey = decodeURIComponent(key);
const index = this.tabs.findIndex(
(item) => getTabPath(item) === originKey,
(item) => getTabKeyFromTab(item) === originKey,
);
if (index === -1) {
return;
@ -290,12 +296,12 @@ export const useTabbarStore = defineStore('core-tabbar', {
},
/**
*
* @param path
* tabkeytab
* @param key
*/
getTabByPath(path: string) {
getTabByKey(key: string) {
return this.getTabs.find(
(item) => getTabPath(item) === path,
(item) => getTabKeyFromTab(item) === key,
) as TabDefinition;
},
/**
@ -311,22 +317,19 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @param tab
*/
async pinTab(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
if (index !== -1) {
const oldTab = this.tabs[index];
tab.meta.affixTab = true;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index === -1) {
return;
}
const oldTab = this.tabs[index];
tab.meta.affixTab = true;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
// 过滤固定tabs后面更改affixTabOrder的值的话可能会有问题目前行464排序affixTabs没有设置值
const affixTabs = this.tabs.filter((tab) => isAffixTab(tab));
// 获得固定tabs的index
const newIndex = affixTabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
const newIndex = affixTabs.findIndex((item) => equalTab(item, tab));
// 交换位置重新排序
await this.sortTabs(index, newIndex);
},
@ -371,9 +374,7 @@ export const useTabbarStore = defineStore('core-tabbar', {
if (tab?.meta?.newTabTitle) {
return;
}
const findTab = this.tabs.find(
(item) => getTabPath(item) === getTabPath(tab),
);
const findTab = this.tabs.find((item) => equalTab(item, tab));
if (findTab) {
findTab.meta.newTabTitle = undefined;
await this.updateCacheTabs();
@ -401,13 +402,24 @@ export const useTabbarStore = defineStore('core-tabbar', {
/**
* @zh_CN
* @param tab
* @param title
*
* @zh_CN
* @zh_CN ,
* @zh_CN
*
* @param {TabDefinition} tab -
* @param {ComputedRef<string> | string} title - ,
*
* @example
* // 设置静态标题
* setTabTitle(tab, '新标签页');
*
* @example
* // 设置动态标题
* setTabTitle(tab, computed(() => t('common.dashboard')));
*/
async setTabTitle(tab: TabDefinition, title: string) {
const findTab = this.tabs.find(
(item) => getTabPath(item) === getTabPath(tab),
);
async setTabTitle(tab: TabDefinition, title: ComputedRef<string> | string) {
const findTab = this.tabs.find((item) => equalTab(item, tab));
if (findTab) {
findTab.meta.newTabTitle = title;
@ -448,17 +460,15 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @param tab
*/
async unpinTab(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
if (index !== -1) {
const oldTab = this.tabs[index];
tab.meta.affixTab = false;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index === -1) {
return;
}
const oldTab = this.tabs[index];
tab.meta.affixTab = false;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
// 过滤固定tabs后面更改affixTabOrder的值的话可能会有问题目前行464排序affixTabs没有设置值
const affixTabs = this.tabs.filter((tab) => isAffixTab(tab));
// 获得固定tabs的index,使用固定tabs的下一个位置也就是活动tabs的第一个位置
@ -591,11 +601,49 @@ function isTabShown(tab: TabDefinition) {
}
/**
* @zh_CN
* routetabkey
* @param tab
*/
function getTabPath(tab: RouteRecordNormalized | TabDefinition) {
return decodeURIComponent((tab as TabDefinition).fullPath || tab.path);
function getTabKey(tab: RouteLocationNormalized | RouteRecordNormalized) {
const {
fullPath,
path,
meta: { fullPathKey } = {},
query = {},
} = tab as RouteLocationNormalized;
// pageKey可能是数组查询参数重复时可能出现
const pageKey = Array.isArray(query.pageKey)
? query.pageKey[0]
: query.pageKey;
let rawKey;
if (pageKey) {
rawKey = pageKey;
} else {
rawKey = fullPathKey === false ? path : (fullPath ?? path);
}
try {
return decodeURIComponent(rawKey);
} catch {
return rawKey;
}
}
/**
* tabtabkey
* tabkey,routekey
* @param tab
*/
function getTabKeyFromTab(tab: TabDefinition): string {
return tab.key ?? getTabKey(tab);
}
/**
* tab
* @param a
* @param b
*/
function equalTab(a: TabDefinition, b: TabDefinition) {
return getTabKeyFromTab(a) === getTabKeyFromTab(b);
}
function routeToTab(route: RouteRecordNormalized) {
@ -603,5 +651,8 @@ function routeToTab(route: RouteRecordNormalized) {
meta: route.meta,
name: route.name,
path: route.path,
key: getTabKey(route),
} as TabDefinition;
}
export { getTabKey };

View File

@ -19,7 +19,7 @@ const checkValue = ref(['a', 'b']);
const options = [
{ label: '选项1', value: 'a' },
{ label: '选项2', value: 'b' },
{ label: '选项2', value: 'b', num: 999 },
{ label: '选项3', value: 'c' },
{ label: '选项4', value: 'd' },
{ label: '选项5', value: 'e' },
@ -168,10 +168,11 @@ function onBtnClick(value: any) {
:options="options"
v-bind="compProps"
>
<template #option="{ label, value }">
<template #option="{ label, value, data }">
<div class="flex items-center">
<span>{{ label }}</span>
<span class="ml-2 text-gray-400">{{ value }}</span>
<span v-if="data.num" class="white ml-2">{{ data.num }}</span>
</div>
</template>
</VbenCheckButtonGroup>