VUE 动态移除缓存路由

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 即可

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文://www.greatytc.com/p/0cdf51904afb 计算属性如何使用 一般我们在写...
    L_b115阅读 807评论 0 0
  • Vue-Music 一| 前期工作 1.项目初始化 npm install -g vue-cli vue init...
    noobakong阅读 1,874评论 0 5
  • 原文地址:vue基本面试题 1、vue双向数据绑定? vue数据双向绑定是通过 数据劫持 结合 发布者-订阅者 模...
    Eldest阅读 2,890评论 1 0
  • vue去哪网跟学笔记 记录学习点滴 1. 初始化项目 1.1 手机显示配适 minimum-scale=1.0,m...
    noobakong阅读 2,295评论 0 16
  • [TOC] 配置Yum仓库 第一步:进入Yum配置文件目录 进入到 /etc/yum.repos.d/ 目录中(该...
    CC晨_程序小生阅读 7,356评论 0 1