美文网首页
vue页面缓存,keep-alive第一次无效的解决方法

vue页面缓存,keep-alive第一次无效的解决方法

作者: ClownD | 来源:发表于2023-03-06 16:55 被阅读0次

我的业务需求是
在一个列表页 这个列表页有分类的标签 有筛选条件 当用户选择后进入详情页需要保留这些数据 退回是筛选条件还在 当时想的肯定是用keep-alive缓存了 但是我发现了一个问题 就是第一次从详情页退回不会缓存 第二次才会。解决办法:

方法一

   <keep-alive >
      <router-view v-if="this.$route.meta.keepAlive" ></router-view>
    </keep-alive>
  <router-view v-if="!this.$route.meta.keepAlive"></router-view>

在keep-alive中添加缓存条件

在详情页面

  beforeRouteLeave(to,from,next){
    console.log(to)
    if(to.name == 'order_list'){
      console.log(to.name)
      to.meta.keepAlive = true
        next()
    }else{
      next()
    }
  },

方法二

不在使用keep-alive缓存页面,改用vuex保存搜索的条件和分页,返回页面时重新赋值获取数据。

在列表页

SET_PARAMS,在vuex中mutations定义保存数据

   //  保存搜索条件和翻页
  beforeRouteLeave(to, form, next) {
    //判断是否进入详情页,进入详情页保存搜索条件params,否则清空数据
    if (to.name == "viewcase") {
      //SET_PARAMS,vuex中mutations,设置listParams的值
      store.commit('app/SET_PARAMS', this.params)
    } else {
      store.commit('app/SET_PARAMS', {})
    }
    next();
  },

created() {
    let data = this.$store.getters.listParams;
    //判断是否有缓存数据
    if (Object.keys(data).length!=0) {
      this.params = data ;
    } 
}

相关文章

网友评论

      本文标题:vue页面缓存,keep-alive第一次无效的解决方法

      本文链接:https://www.haomeiwen.com/subject/izvmldtx.html