vue 中使用keepAlive状态保持

 

  

keepAlive状态保持

1 主要实现原理,状态保持的路由不会执行生命周期的钩子函数,只有第一次进入页面会执行钩子函数。
2 设置当前页面保持keepAlive  直接在路由meta中配置即可 
meta{
keepALive:true
}

<keep-alive>
  <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
 
actived :这也是一个钩子函数,keepAlive状态保持的页面中生命周期的钩子函数不会触发,但是会触发actived钩子函数,那么这样可操作性就很大了。
2 keepalive 状态保持的页面对应的会又一个actived钩子函数,每次进入页面都会执行的函数,在keepalive状态保持的路由,如果需要加载created,
可以在actived钩子函数中执行,切记第一次进入会执行生命周期函数同时actived钩子函数也会执行 ,
必要情况进行判断,避免两个函数都执行造成数据渲染问题,路由跳转等问题。
 3 在局部导航守卫中修改keepalive的值,为true或者false,修改之后同样第一次会执行created 和 actived钩子函数,
需要根据业务需求进行处理。 (代码参考结合实际项目)
 演示一 : actived中执行的 activated() 
{ if ( this.cancel==='取消订单' )
{ console.log('取消订单');
 this.active='已取消'; this.parameterObj.orderStatus ='3,4,5';
 this.listDate=[]; if(this.uniqueID)
{ this.listDate=[]; this.parameterObj.uniqueID=this.uniqueID; this.renderOrderList(); }
 this.setCancelOrderAction({cancel:''}); }
 if(this.$route.params.orderListActive === 1)
{ if(this.uniqueID){ this.parameterObj.uniqueID=this.uniqueID; this.active='待付款'; this.parameterObj.orderStatus='0,2'; this.listDate = []; 
this.renderOrderList() } } if(this.$route.params.orderListActive === 0){ if(this.uniqueID){ this.parameterObj.uniqueID=this.uniqueID; this.active='全部'; 
this.parameterObj.orderStatus='0,1,2,3,4,5'; this.listDate = []; this.renderOrderList() } } 演示二:created中执行的 ,在created中进行判断避免执行created中的函数 
if ( this.cancel==='取消订单' ){ return } else if(this.$route.params.orderListActive === 1)
{ return } else if(this.$route.params.orderListActive === 0){ return } else { if(this.uniqueID)
{ console.log(222); this.parameterObj.uniqueID=this.uniqueID; this.listDate = []; this.renderOrderList(); }
else { this.getAppUserInfo(); } }
  
  
  

  

原文地址:https://www.cnblogs.com/tiangeng/p/9917612.html