清空 keep-alive 缓存

280 阅读1分钟

解决因为路由配置了 keepalive 而造成的状态缓存问题。 原理:在页面离开之后,清空实例上的当前页面缓存。

beforeRouteLeave: function (to, from, next) {
    // 清除 keep alive 缓存
    if (this.$vnode && this.$vnode.data.keepAlive) {
      if (this.$vnode.parent && this.$vnode.parent.componentInstance) {
        const key = this.$vnode.key;
        const cache = this.$vnode.parent.componentInstance.cache;
        const keys = this.$vnode.parent.componentInstance.keys;
        if (cache[key]) {
          // this.$destroy();
          let index = keys.indexOf(key);
          if (index > -1) {
            keys.splice(index, 1);
          }
          delete cache[key];
        }
      }
    }
    next();
  },