vue中使用keepAlive组件缓存遇到的坑

2019-12-14 20:58:46

参考地址 vue中使用keepAlive组件缓存遇到的坑

项目开发中在用户由分类页category进入detail需保存用户状态,查阅了Vue官网后,发现vue2.0提供了一个keep-alive组件。

上一篇讲了keep-alive的基本用法,现在说说遇到的坑。

先说项目中的配置

 

在App.vue中的设置

 

在router中增加配置meta

  

 

上面这个设置后发现问题了,从category进入detail页后,状态被保存了,返回的时候保存了用户状态,达到了预期效果

但问题在于但从category返回到index后,再由index进入category时依然显示是缓存中的页面,此刻页面没有刷新。

返回index后的组件显示如下:

   

分析从index再次进入category时,直接读取了缓存的里的页面。

头大。。。。。。。我的目标只是缓存从category进入detail页面,其他的时候不缓存。

 

 

解决方案

在category中启用beforeRouteLeave钩子函数

beforeRouteLeave中只有从category进入detail时才进行缓存,其他页面都讲category的keepalive设置成false,并销毁此category组件;

 

然而,发现新的问题。。。。。。

第一次操作index--> category ---> detail的时候是理想效果,但当第二次操作返回index后,进行index --> category --> detail --> category时,发现缓存的对象又不对了,从detail返回category时,保存是的第一次进入detail的分类情况。

此刻category的组件显示如下

 

 

无奈。。。。。对比了第一次和第二次进入页面情况

 

根据vue-router提供的守卫可在路由中启用afterEach路由守卫,在afterEach中进行判断是否第一次进入,非第一次进入页面情况强制刷新一次category页面。 

 

 

至此终于解决了这个问题。

 

网友提供了其他的解决方案可以参考下,

https://www.jianshu.com/p/cd1baf5b03b0

也可以参考github上关于keep-alive缓存相关的问。

https://github.com/vuejs/vue-router/issues/811#issuecomment-353875880


  • 2018-02-23 14:22:50

    mysql的yearweek 和 weekofyear函数

    例如 2010-3-14 ,礼拜天 SELECT YEARWEEK('2010-3-14') 返回 11 SELECT YEARWEEK('2010-3-14',1) 返回 10 其中第二个参数是 mode ,具体指的意思如下: Mode First day of week Range Week 1 is the first week … 0 Sunday 0-53 with a Sunday in this year 1 Monday 0-53 with more than 3 days this year 2 Sunday 1-53 with a Sunday in this year 3 Monday 1-53 with more than 3 days this year 4 Sunday 0-53 with more than 3 days this year 5 Monday 0-53 with a Monday in this year 6 Sunday 1-53 with more than 3 days this year 7 Monday 1-53 with a Monday in this year 2.

  • 2018-02-23 17:20:44

    Mysql数据库If语句的使用

    MySQL的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用:

  • 2018-02-24 10:16:36

    Java工具类之Apache的Commons Lang和BeanUtils

    Apache Commons包估计是Java中使用最广发的工具包了,很多框架都依赖于这组工具包中的一部分,它提供了我们常用的一些编程需要,但是JDK没能提供的机能,最大化的减少重复代码的编写。