Files
new_wms_admin/src/stores/modules/tabs.ts
2025-10-16 15:35:43 +08:00

100 lines
4.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import router from "@/routers";
import { defineStore } from "pinia";
import { TabsState } from "@/stores/interface";
import piniaPersistConfig from "@/config/piniaPersist";
export const useTabsStore = defineStore({
id: "wms-tabs",
state: (): TabsState => ({
tabsMenuList: [
{
icon: "", // 首页的icon按实际路由meta.icon填写如"Home"
title: "首页", // 固定首页标题
path: "/index", // 首页的基础路径(无参数版本,避免初始参数冗余)
name: "home", // 必须与首页路由的name一致如路由定义中name: "home"
close: true // 首页是否可关闭按业务需求设置通常true若禁止关闭设为false
}
]
}),
actions: {
// Add Tabs按 name 去重,首页始终在最前
async addTabs(tabItem: any) {
// 1. 校验参数:确保 tabItem 有 name避免异常数据
if (!tabItem.name) return;
// 2. 去重逻辑:按 name 判断是否已存在
const isExist = this.tabsMenuList.some(item => item.name === tabItem.name);
if (!isExist) {
// 3. 首页name: "home")添加到数组开头,其他标签添加到末尾
if (tabItem.name === "home") {
// 先移除旧的首页(防止极端情况残留),再添加新首页到最前
this.tabsMenuList = this.tabsMenuList.filter(item => item.name !== "home");
this.tabsMenuList.unshift(tabItem); // 首页放第一位
} else {
this.tabsMenuList.push(tabItem); // 非首页放末尾
}
} else {
// 4. 可选优化:若标签已存在,同步更新其 path如首页参数变化时
this.tabsMenuList = this.tabsMenuList.map(item => {
if (item.name === tabItem.name) {
return { ...item, path: tabItem.path }; // 仅更新 path保留其他属性
}
return item;
});
}
},
// Remove Tabs原有逻辑不变无需修改
async removeTabs(tabPath: string, isCurrent: boolean = true) {
const tabsMenuList = this.tabsMenuList;
if (isCurrent) {
tabsMenuList.forEach((item, index) => {
if (item.path !== tabPath) return;
const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1];
if (!nextTab) return;
router.push(nextTab.path);
});
}
this.tabsMenuList = tabsMenuList.filter(item => item.path !== tabPath);
},
// Close MultipleTab原有逻辑不变
async closeMultipleTab(tabsMenuValue?: string) {
this.tabsMenuList = this.tabsMenuList.filter(item => {
return item.path === tabsMenuValue || !item.close;
});
},
// Set Tabs原有逻辑不变
async setTabs(tabsMenuList: any[]) {
// 补充:设置 tabs 时也需去重,避免批量设置时带入重复首页
const uniqueTabs = [];
const nameSet = new Set();
// 先处理首页,确保在最前
const homeTab = tabsMenuList.find(item => item.name === "home");
if (homeTab) {
uniqueTabs.push(homeTab);
nameSet.add("home");
}
// 再处理其他标签,去重
tabsMenuList.forEach(tab => {
if (!nameSet.has(tab.name)) {
nameSet.add(tab.name);
uniqueTabs.push(tab);
}
});
this.tabsMenuList = uniqueTabs;
},
// Set Tabs Title原有逻辑不变
async setTabsTitle(title: string) {
const nowFullPath = location.hash.substring(1);
this.tabsMenuList.forEach(item => {
if (item.path == nowFullPath) item.title = title;
});
}
},
persist: piniaPersistConfig("wms-tabs")
});