清除keepalive缓存

本文介绍了如何在Vue应用中使用KeepAlive组件实现A页面在B页面返回时保持数据不刷新,同时在跳转到C页面时清除A页面的缓存。详细描述了A页面的beforeRouteLeave钩子函数用于控制缓存操作。
摘要由CSDN通过智能技术生成

背景:

A页面进入B页面,返回A后页面不刷新,保留数据。A页面进入C页面,返回A页面刷新

实现:
对A页面进行keepalive,进入C,清除缓存。

代码:

App.vue页面

 <div id="app">
    <KeepAlive>
      <router-view v-if="$route.meta.KeepAlive"/>
    </KeepAlive>
    <router-view v-if="!$route.meta.KeepAlive"/>
  </div>

route.js

{
  path: "/A",
  name:'A',
  meta: { 
    KeepAlive:true
  },
  component: () =>
      import ('../vue/A'),
},

A页面

beforeRouteLeave(to, from, next) {
      console.log('---beforeRouteLeave')
      if(to.name != 'B'){
        // 清楚缓存
        let Vnode = this.$vnode;
        let parentVnode = Vnode && Vnode.parent;
        if (parentVnode && parentVnode.componentInstance && parentVnode.componentInstance.cache) {
            var key = Vnode.key == null ? Vnode.componentOptions.Ctor.cid + (Vnode.componentOptions.tag ? `::${Vnode.componentOptions.tag}` : '') : Vnode.key;
            var cache = parentVnode.componentInstance.cache;
            var keys  = parentVnode.componentInstance.keys;
            if (cache[key]) {
                this.$destroy();
                if (keys.length) {
                    var index = keys.indexOf(key);
                    if (index > -1) {
                        keys.splice(index, 1);
                    }
                }
                cache[key] = null;
            }
        }
      }
     
      next()
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cola-blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值