设计标签页右键菜单(刷新/关闭其他)
解读
在国内 B 端后台、SaaS、低代码平台面试中,标签页右键菜单是高频实战题。
它考察的不是“能不能弹出菜单”,而是:
- 如何在组件层面管理多标签状态(刷新、关闭、顺序、缓存)。
- 如何防止事件冒泡、避免浏览器原生菜单、兼容移动端长按。
- 如何与 Vue/React 生态结合(keep-alive、Suspense、React-Router v6 的 loader)。
- 如何在关闭后自动聚焦相邻标签并同步路由(Vue Router 的 replace、React Router 的 navigate(-1))。
- 如何在刷新时保留滚动位置与表单状态(pinia/vuex、redux-persist、sessionStorage)。
- 如何做无障碍(role="menu"、aria-haspopup、键盘↑↓回车关闭)。
- 如何做自动化测试(@vue/test-utils 右键触发 contextmenu、jest-user-event)。
一句话:把“右键”当入口,把“标签系统”当核心,把“性能+可维护+可测”当底线。
知识点
- 事件拦截:
e.preventDefault()+e.stopPropagation(),兼容火狐shift+F10。 - 定位算法:视口边界检测,getBoundingClientRect + window.innerWidth/Height,防止菜单超出。
- 状态设计:
- 用 Map<tabId, {keepAliveKey, scrollTop, formSnapshot}> 缓存刷新现场。
- 用 computed 派生“可关闭列表” 过滤固定页(如首页)。
- 刷新策略:
- Vue:动态移除 keep-alive 的 include 数组,nextTick 后加回,强制重新挂载。
- React:给
<Route key={Date.now()} />变化 key,或利用useRevalidator(RRv6.4)。
- 关闭其他:
- 批量调用 router.replace() 避免多次 history 写入。
- 用 queueMicrotask 保证 DOM 更新后再聚焦相邻 tab,防止焦点丢失。
- 指令封装:Vue 自定义指令
v-contextmenu、React 高阶组件withContextMenu,方便复用。 - 性能:
- 右键菜单用 Teleport/Portal 挂载 body,减少层叠上下文问题。
- 监听
resize与scroll自动隐藏菜单,防抖 16 ms 保证 60 fps。
- 安全:菜单项命令用 Symbol 注册,防止 XSS 通过字符串注入。
- 测试:
- 单元:@testing-library/user-event 的
pointer({keys: '[MouseRight]'})。 - e2e:Playwright 的
contextmenu+expect(page.url()).toContain(targetRoute)。
- 单元:@testing-library/user-event 的
答案
以下给出 Vue3 + TS + Pinia 的完整最小可运行方案,React 思路同源,可平替。
- 状态层(stores/tabs.ts)
export interface TabItem {
id: string;
path: string;
title: string;
affix?: boolean; // 固定标签,不可关闭
keepAliveKey?: string; // 对应 keep-alive 的 key
scrollPos?: { x: number; y: number };
}
export const useTabsStore = defineStore('tabs', () => {
const tabs = ref<TabItem[]>([]);
const activeId = ref<string>('');
function addTab(item: TabItem) { /* 去重后 push */ }
function closeTab(id: string) {
const idx = tabs.value.findIndex(t => t.id === id);
if (idx === -1) return;
tabs.value.splice(idx, 1);
// 自动聚焦相邻
if (activeId.value === id) {
const next = tabs.value[idx] || tabs.value[idx - 1];
if (next) router.replace(next.path);
}
}
function closeOthers(id: string) {
const target = tabs.value.find(t => t.id === id);
if (!target) return;
tabs.value = tabs.value.filter(t => t.affix || t.id === id);
if (activeId.value !== id) router.replace(target.path);
}
function refresh(id: string) {
const target = tabs.value.find(t => t.id === id);
if (!target) return;
// 记录滚动位置
target.scrollPos = { x: window.scrollX, y: window.scrollY };
// 移除 keep-alive 缓存
const key = target.keepAliveKey || target.path;
const set = new Set(keepAliveInclude.value);
set.delete(key);
keepAliveInclude.value = Array.from(set);
nextTick(() => {
set.add(key);
keepAliveInclude.value = Array.from(set);
// 恢复滚动位置
nextTick(() => {
if (target.scrollPos) {
window.scrollTo(target.scrollPos.x, target.scrollPos.y);
}
});
});
}
return { tabs, activeId, addTab, closeTab, closeOthers, refresh };
});
- 右键菜单组件(components/ContextMenu.vue)
<template>
<Teleport to="body">
<Transition name="fade">
<ul
v-if="visible"
:style="{ left: pos.x + 'px', top: pos.y + 'px' }"
class="context-menu"
role="menu"
tabindex="-1"
@contextmenu.prevent
>
<li role="menuitem" @click="onRefresh">刷新</li>
<li role="menuitem" @click="onCloseOthers">关闭其他</li>
</ul>
</Transition>
</Teleport>
</template>
<script setup lang="ts">
import { onClickOutside, onKeyStroke } from '@vueuse/core';
const visible = ref(false);
const pos = reactive({ x: 0, y: 0 });
let targetId = '';
function open(e: MouseEvent, id: string) {
e.preventDefault();
targetId = id;
const { clientX, clientY } = e;
const { innerWidth, innerHeight } = window;
const menuWidth = 120;
const menuHeight = 80;
pos.x = clientX + menuWidth > innerWidth ? innerWidth - menuWidth : clientX;
pos.y = clientY + menuHeight > innerHeight ? innerHeight - menuHeight : clientY;
visible.value = true;
}
function onRefresh() {
useTabsStore().refresh(targetId);
close();
}
function onCloseOthers() {
useTabsStore().closeOthers(targetId);
close();
}
function close() { visible.value = false; }
onClickOutside(document.querySelector('.context-menu') as HTMLElement, close);
onKeyStroke('Escape', close);
defineExpose({ open });
</script>
<style scoped>
.context-menu { position: fixed; z-index: 9999; background: #fff; border: 1px solid #e0e0e0; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,.15); padding: 4px 0; }
.context-menu li { list-style: none; padding: 6px 16px; cursor: pointer; font-size: 14px; }
.context-menu li:hover { background: #f5f5f5; }
.fade-enter-active, .fade-leave-active { transition: opacity .15s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>
- 标签栏组件(components/TabBar.vue)
<template>
<div class="tab-bar">
<div
v-for="t in tabs"
:key="t.id"
class="tab"
:class="{ active: t.id === activeId }"
@contextmenu="onContext($event, t.id)"
>
{{ t.title }}
</div>
</div>
<ContextMenu ref="menu" />
</template>
<script setup lang="ts">
const store = useTabsStore();
const { tabs, activeId } = storeToRefs(store);
const menu = ref<InstanceType<typeof ContextMenu>>();
function onContext(e: MouseEvent, id: string) {
menu.value?.open(e, id);
}
</script>
- 路由守卫自动加签
router.afterEach((to) => {
useTabsStore().addTab({ id: to.fullPath, path: to.fullPath, title: to.meta?.title || '未命名' });
});
- 测试用例(jest + vue-test-utils)
it('右键关闭其他', async () => {
const wrapper = mount(TabBar);
const tabs = wrapper.findAll('.tab');
await tabs[1].trigger('contextmenu');
const menu = document.querySelector('.context-menu')!;
const closeOthers = menu.querySelector('li:nth-child(2)')!;
await fireEvent.click(closeOthers);
expect(useTabsStore().tabs.length).toBe(1);
});
拓展思考
- 多窗口协同:当用户拖拽标签出浏览器成为独立窗口时,需借助 BroadcastChannel 同步关闭/刷新指令,避免状态孤岛。
- 权限控制:某些标签含敏感数据,关闭其他时需二次确认,可封装 useBeforeClose 钩子,返回 Promise,await ElMessageBox.confirm()。
- 性能极限:当标签数 >100,keep-alive 内存爆炸,可引入 LRU 缓存策略,结合 WeakMap 记录组件实例,动态卸载最久未激活标签。
- 微前端场景:在 qiankun 下,子应用标签刷新不能直接替换路由,需调用 props.refresh() 由主应用下发 single-spa 的 unloadApplication,再 re-mount。
- 可视化拖拽排序:集成 vuedraggable/react-beautiful-dnd,拖拽后同步 tabs 数组顺序,并持久化到 IndexedDB,刷新页面可还原。