export const useTagsViewStore = defineStore('tagsView', {
state: (): TagsViewState => ({
visitedViews: [],
cachedViews: new Set()
}),
getters: {
getVisitedViews(): RouteLocationNormalizedLoaded[] {
return this.visitedViews
},
getCachedViews(): string[] {
return Array.from(this.cachedViews)
}
},
actions: {
// 新增缓存和tag
addView(view: RouteLocationNormalizedLoaded): void {
this.addVisitedView(view)
this.addCachedView()
},
// 新增tag
addVisitedView(view: RouteLocationNormalizedLoaded) {
if (this.visitedViews.some((v) => v.path === view.path)) return
if (view.meta?.noTagsView) return
this.visitedViews.push(
Object.assign({}, view, {
title: view.meta?.title || 'no-name'
})
)
},
// 新增缓存
addCachedView() {
const cacheMap: Set<string> = new Set()
for (const v of this.visitedViews) {
const item = getRawRoute(v)
const needCache = !item.meta?.noCache
if (!needCache) {
continue
}
const name = item.name as string
cacheMap.add(name)
}
if (Array.from(this.cachedViews).sort().toString() === Array.from(cacheMap).sort().toString())
return
this.cachedViews = cacheMap
},
// 删除某个
delView(view: RouteLocationNormalizedLoaded) {
this.delVisitedView(view)
this.delCachedView()
},
// 删除tag
delVisitedView(view: RouteLocationNormalizedLoaded) {
for (const [i, v] of this.visitedViews.entries()) {
if (v.path === view.path) {
this.visitedViews.splice(i, 1)
break
}
}
},
// 删除缓存
delCachedView() {
const route = router.currentRoute.value
const index = findIndex<string>(this.getCachedViews, (v) => v === route.name)
if (index > -1) {
this.cachedViews.delete(this.getCachedViews[index])
}
}
})
这两个函数的目标确实都是找到特定条件下的某一项并将其从集合中删除,但它们的实现方式和数据结构不同。
delVisitedView
函数
- 实现方法:使用
for...of
循环和entries()
方法遍历visitedViews
数组。 - 数据结构:处理的是数组,使用
splice()
方法删除元素。 - 优势:在处理数组时,
splice()
直接修改原数组,适合需要频繁进行元素插入或删除的场景。
delCachedView
函数
- 实现方法:使用
findIndex()
函数查找当前路由的索引,并调用delete()
方法从cachedViews
集合中删除。 - 数据结构:处理的是
Set
,适合存储唯一值。 - 优势:
Set
提供了更好的性能用于查找和删除元素,且自动确保元素唯一性。
总结
delVisitedView
适合需要顺序和可重复元素的场景。delCachedView
适合需要唯一元素的情况,且操作性能更优。