// stores/tabs.ts — Issue#2 多标签导航(tags-view)状态。 // // 设计口径(tab 身份=route.fullPath,缓存身份=组件名=路由名): // - keep-alive :include 按**组件名**匹配,而 script setup 的文件名推断名 // (15 个 index.vue 全叫 "index";PascalCase 文件名 ≠ kebab 路由名)永不 // 命中——各业务视图必须 defineOptions({ name: <路由名> }),守门测试 // tests/view-cache-name.spec.ts 防新增页面漏写导致"缓存静默失效"。 // - tab 身份用 fullPath:参数页(account/:id、channel/edit/:id?)每实例 // 一 tab;query 变体亦独立成 tab(口径如此,验收单有记)。 // - ComingSoon 占位页(11 条路由共用)**豁免缓存**:无本地状态可保, // 不写 defineOptions → include 永不命中 → 每次进入重挂载,零副作用。 // - 同名多实例(如 account/1 与 account/2)关闭其一时缓存条目随名保留, // 最后一个同名 tab 关闭才真正释放(keep-alive 按名驱逐,有限驻留可接受)。 import { defineStore } from 'pinia' import type { RouteLocationNormalizedLoaded } from 'vue-router' export interface TabItem { path: string // fullPath(tab 身份:去重锚+跳转目标) name: string // 路由名(=组件名,keep-alive include 锚) title: string // 标签文案(meta.title + 参数后缀) affix?: boolean // 固定标签(home,不可关闭) } /** 固定标签:运营总览(五角色可达;刷新后的最小恢复集)。 */ const AFFIX_HOME: TabItem = { path: '/home', name: 'home', title: '运营总览', affix: true } /** 参数页标题后缀:账号详情 #12 / 通道编辑 #7(无 id 的新建态不加后缀)。 */ function tabTitle(route: RouteLocationNormalizedLoaded): string { const base = String(route.meta.title ?? '') const id = route.params?.id return id ? `${base} #${String(id)}` : base } /** 开标签判据:业务页(有 title+group);错误页(403/500/404)无 group 不开, * 登录页在布局外、redirect 路由永不成为 resolved 终路由,均天然排除。 */ function isTabbed(route: RouteLocationNormalizedLoaded): boolean { return typeof route.name === 'string' && !!route.meta.title && !!route.meta.group } interface TabsState { visited: TabItem[] } export const useTabsStore = defineStore('tabs', { state: (): TabsState => ({ visited: [{ ...AFFIX_HOME }] }), getters: { /** keep-alive include 列表:打开中的 tab 的路由名(=组件名,去重)。 */ cachedNames: (s): string[] => [...new Set(s.visited.map((t) => t.name))], }, actions: { /** 路由到达即登记(按 fullPath 去重;标题随参数刷新)。 */ addTab(route: RouteLocationNormalizedLoaded) { if (!isTabbed(route)) return const exists = this.visited.find((t) => t.path === route.fullPath) if (exists) { exists.title = tabTitle(route) return } this.visited.push({ path: route.fullPath, name: String(route.name), title: tabTitle(route) }) }, /** 关闭单个标签;若关的是当前页则返回应跳转的相邻 tab path * (右邻优先,末位取左邻),否则返回 null(无需导航)。固定标签不可关。 */ close(path: string, activePath: string): string | null { const idx = this.visited.findIndex((t) => t.path === path) if (idx < 0 || this.visited[idx]!.affix) return null this.visited.splice(idx, 1) if (path !== activePath) return null const neighbor = this.visited[Math.min(idx, this.visited.length - 1)] return neighbor ? neighbor.path : '/home' }, /** 关闭其他(固定标签与当前页保留)。 */ closeOthers(keepPath: string) { this.visited = this.visited.filter((t) => t.affix || t.path === keepPath) }, /** 全部关闭(仅固定标签保留);返回回退目标。 */ closeAll(): string { this.visited = this.visited.filter((t) => t.affix) return this.visited[0]?.path ?? '/home' }, }, })