81 lines
1.9 KiB
JavaScript
81 lines
1.9 KiB
JavaScript
import { defineStore } from 'pinia'
|
|
import { ref } from 'vue'
|
|
import router from '@/router'
|
|
|
|
export const useTabsStore = defineStore('tabs', () => {
|
|
const defaultTabs = [{
|
|
title: '首页',
|
|
path: '/home',
|
|
name: 'home',
|
|
fixed: true
|
|
}]
|
|
|
|
const tabs = ref(JSON.parse(sessionStorage.getItem('tabs')) || defaultTabs)
|
|
const activeTab = ref(sessionStorage.getItem('activeTab') || '/home')
|
|
|
|
// 添加标签页
|
|
const addTab = (route) => {
|
|
if (route.meta?.noTab || route.meta?.hidden) {
|
|
return
|
|
}
|
|
|
|
const isExist = tabs.value.some(tab => tab.path === route.path)
|
|
if (!isExist) {
|
|
tabs.value.push({
|
|
title: route.meta.title,
|
|
path: route.path,
|
|
name: route.name,
|
|
fixed: false
|
|
})
|
|
}
|
|
activeTab.value = route.path
|
|
saveToStorage()
|
|
}
|
|
|
|
// 移除标签页
|
|
const removeTab = (targetPath) => {
|
|
const targetIndex = tabs.value.findIndex(tab => tab.path === targetPath)
|
|
if (targetIndex === -1 || tabs.value[targetIndex].fixed) return
|
|
if (activeTab.value === targetPath) {
|
|
const nextTab = tabs.value[targetIndex + 1] || tabs.value[targetIndex - 1]
|
|
if (nextTab) {
|
|
activeTab.value = nextTab.path
|
|
router.push(nextTab.path)
|
|
}
|
|
}
|
|
|
|
tabs.value.splice(targetIndex, 1)
|
|
saveToStorage()
|
|
}
|
|
|
|
// 切换标签页
|
|
const switchTab = (path) => {
|
|
activeTab.value = path
|
|
router.push(path)
|
|
saveToStorage()
|
|
}
|
|
|
|
|
|
// 保存到sessionStorage
|
|
const saveToStorage = () => {
|
|
sessionStorage.setItem('tabs', JSON.stringify(tabs.value))
|
|
sessionStorage.setItem('activeTab', activeTab.value)
|
|
}
|
|
|
|
// 清空标签页
|
|
const clearTabs = () => {
|
|
tabs.value = [...defaultTabs]
|
|
activeTab.value = '/home'
|
|
sessionStorage.removeItem('tabs')
|
|
sessionStorage.removeItem('activeTab')
|
|
}
|
|
|
|
return {
|
|
tabs,
|
|
activeTab,
|
|
addTab,
|
|
removeTab,
|
|
switchTab,
|
|
clearTabs
|
|
}
|
|
})
|