vue技术栈Vuevue

VUE 动态移除缓存路由

2019-07-12  本文已影响120人  骑着母猪去买菜

VUE 动态移除缓存路由

在缓存路由时,有时候需要将缓存的路由清除掉达到刷新页面数据的效果。方法如下:

  1. 配置路由时,在路由元信息中添加该路由是否需要被缓存的标识:

    // routes.js
    export default [
        {
            path: '/list',
            name: 'list',
            meta: {
                title: '列表',
                notCache: false
            }
        }
    ]
    
  1. <keep-alive> 标签上绑定 include 属性,从 vuex 获取当前缓存的组件名数组:

    <!-- Main.vue -->
    <template>
        <keep-alive :include="cacheList"></keep-alive>
    </template>
    
    <script>
        import {mapGetters} from 'vuex'
        export default {
            name: 'Main',
            computed: {
                ...mapGetters([
                    'tagsList'
                ])
                cacheList() {
                    let cacheList = ['home']
                    if (this.tagsList.length) {
                        cacheList = [
                            ...cacheList,
                            ...this.tagsList.filter(item => {
                                return !(item.meta && item.meta.notCache)
                            }).map(item => item.name)
                        ]
                    }
                    return cacheList
                }
            }
        }
    </script>
    
  1. 每次跳转新路由时,将需要缓存的路由存入 vuex 中:

    <!-- Main.vue -->
    <script>
        export default {
            name: 'Main',
            watch: {
                '$route'(newRoute) {
                    const {name, path, meta, query, params} = newRoute
                    let newList = [...this.tagsList]
                    let index = newList.findIndex(item => item.name === name)
                    if (!meta.notCache && index < 0) {
                        // 需要缓存
                        newList.push({name, path, meta})
                    }
                }
            }
        }
    </script>
    
    // store.js
    export default {
        state: {
            tagsList: []
        },
        mutations: {
            setTagList(state, list) {
                let tagsList = []
                if (list) {
                    tagsList = [...list]
                } else {
                    // 若有存入localstorage中时可考虑
                    // tagsList = getTagsListFromLocalstorage() || []
                }
            }
        },
        getters: {
            tagsList: state => state.tagsList
        }
    }
    
  2. 在跳转后需要删除路由缓存时,将该路由信息从 tagsList 中删除后,重新调用 vuexsetTagList 即可

上一篇下一篇

猜你喜欢

热点阅读