wujingjing
2024-12-11 2144fb07b53812f565b2801f99e69cee9b28cab3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { defineStore } from 'pinia';
 
/**
 * 路由缓存列表
 * @methods setCacheKeepAlive 设置要缓存的路由 names(开启 Tagsview)
 * @methods putCachedView 添加要缓存的路由 names(关闭 Tagsview)
 * @methods delCachedView 删除要缓存的路由 names(关闭 Tagsview)
 * @methods delOthersCachedViews 右键菜单`关闭其它`,删除要缓存的路由 names(关闭 Tagsview)
 * @methods delAllCachedViews 右键菜单`全部关闭`,删除要缓存的路由 names(关闭 Tagsview)
 */
export const useKeepALiveNames = defineStore('keepALiveNames', {
    state: (): KeepAliveNamesState => ({
        keepAliveNames: [],
        cachedViews: [],
        maxCached: 20,
    }),
    actions: {
        async setCacheKeepAlive(data: Array<string>) {
            this.keepAliveNames = data;
        },
 
        /**
         * 根据 LRU 算法,添加缓存路由
         * 更新缓存列表顺序也可以使用此方法
         * @param view
         * @returns
         */
        async putCachedView(view: any) {
            if (!view.meta.isKeepAlive) return;
            const foundIndex = this.cachedViews.findIndex((item) => item === view.name);
            if (foundIndex > -1) {
                if (foundIndex === this.cachedViews.length - 1) return;
 
                this.cachedViews.splice(foundIndex, 1);
            } else if (this.cachedViews.length >= this.maxCached) {
                this.cachedViews.shift();
            }
            this.cachedViews.push(view.name);
        },
 
        async delCachedView(view: any) {
            const index = this.cachedViews.indexOf(view.name);
            index > -1 && this.cachedViews.splice(index, 1);
        },
        async delOthersCachedViews(view: any) {
            if (view.meta.isKeepAlive) this.cachedViews = [view.name];
            else this.cachedViews = [];
        },
        async delAllCachedViews() {
            this.cachedViews = [];
        },
    },
});