vue给页面加缓存

提到缓存,第一反应就是keep-alive,奈何keepalive的坑实在是踩不过来。下面介绍一下本人使用的方法。

需要加缓存的页面(一般为列表页)

beforeRouteLeave (to, from, next) {
    // ...
    if (to.name === '详情页名字') {
      //去往详情页时需要缓存
      let obj = JSON.parse(JSON.stringify(this.$data))
      obj['$name'] = this.$route.name
      this.$store.commit('cache/updateCache', obj)
    } else {
   	  //否则清空缓存
      this.$store.commit('cache/updateCache', {})
    }
    next()
  },
  created () {
    let data = JSON.parse(JSON.stringify(this.$store.state.cache.cache))
    if (data && data.$name && data.$name === this.$route.name) {
      //有缓存赋值
      for (let k in data) {
        this[k] = data[k]
      }
    } else {
      //无缓存初始化页面
      this.init();
    }
  },

详情或编辑页

beforeRouteLeave (to, from, next) {
    // 返回的不是列表页,清空缓存
    if(to.name != '列表页名字'){
      this.$store.commit('cache/updateCache',{})
    }
    next()
  },

router全局拦截

router.beforeEach((to, from, next) => {
  // 刷新页面时,清除缓存
  if(!from.name){
    store.commit('cache/updateCache', {})
  }
  window.scrollTo(0, 0)
  next()
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值