//APP.vue中
<keep-alive :include="keepAlive">
    <router-view></router-view>
</keep-alive>
//vuex中
state:{
    keepAlive:[]
},
mutations:{
    changeKeepAlive_:(state,keepAlive_)=>{
        if(typeof keepAlive_ == "string"){
            state.keepAlive.push(keepAlive_);
        }else{
            state.keepAlive = keepAlive_;
        }
    }
}
//App.vue中监听路由变化
watch: {
    $route(to,from){
      if(!this.removalArr(to.name) && to.name != "Login"){//如果不存在缓存的组件,并且登录页设置为不缓存
        this.$store.dispatch("changeKeepAlive",to.name);//将此组件添加至缓存中
      }else if(to.name == "Login"){//如果跳转到登录页,需清空所有的缓存
        this.$store.dispatch("changeKeepAlive",[]);//清空
      }
    }
},
methods:{
    removalArr(val){
      for(let i = 0;i<this.keepAlive.length;i++){//查找是否有包含的缓存组件
        if(this.keepAlive[i] == val){//如果有,直接return
          return true;
        }
      }
      return false;
    }
}

 

Logo

前往低代码交流专区

更多推荐