VUE 动态移除缓存路由
在缓存路由时,有时候需要将缓存的路由清除掉达到刷新页面数据的效果。方法如下:
-
配置路由时,在路由元信息中添加该路由是否需要被缓存的标识:
// routes.js export default [ { path: '/list', name: 'list', meta: { title: '列表', notCache: false } } ]
-
在
<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>
-
每次跳转新路由时,将需要缓存的路由存入
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 } }
在跳转后需要删除路由缓存时,将该路由信息从
tagsList
中删除后,重新调用vuex
中setTagList
即可