Vue keepalive缓存清理思路

涉及知识点:vuex,mixins,keepalive,route,computed,watch

 

1./store/index.js  :

   store:  
    keepAliveList:[],
mutations:   setKeepAliveLists(state,keepName){       state.keepAliveList.push(keepName);     },     removeKeepAliveItem(state,keepName){       state.keepAliveList.splice(state.keepAliveList.indexOf(keepName), 1)     },

 

2./components/TopWatch :(非左侧标签导航组件,点击路由切换,可关闭)

    监听路由变化,当其meta.keepAlive为true时将该路由的name存入keepAliveList
    this.$store.commit('setKeepAliveLists',storeCache);
点击关闭标签时,当其meta.keepAlive为true时将该路由的name存入keepAliveList this.$store.commit('removeKeepAliveItem',storeCache);

 

3.引入mixins在需要动态销毁的组件里,监听store.state.keepAliveList

import mixin from '../../mixin'

export default {
    mixins:[mixin],
}

 

4.当mixins所在组件的name不存在于store.state.keepAliveList时,执行this.$destroy()

export default {     computed: {         keepAliveConf(){             return this.$store.state.keepAliveList;         }     },     watch:{         keepAliveConf(e){             // 监听缓存列表的变化,如果缓存列表中没有当前的路由或组件则在缓存中销毁该实例             let name = this.$options.name;             if(!this.$store.state.keepAliveList.includes(name)) {                 this.$destroy()             }         }     }, }

 

上一篇:Socket中KeepAlive设置


下一篇:keepalive实现通知脚本