Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue-动态控制 keep-alive 缓存 #58

Open
PleaseStartYourPerformance opened this issue Jul 1, 2022 · 0 comments
Open

Vue-动态控制 keep-alive 缓存 #58

PleaseStartYourPerformance opened this issue Jul 1, 2022 · 0 comments

Comments

@PleaseStartYourPerformance
Copy link
Owner

const removeKeepAliveCacheForVueInstance = (vueInstance:any) => {
  // 找到组件实例在caches里的key
  let key =
    vueInstance.$vnode.key ??
    vueInstance.$vnode.componentOptions.Ctor.cid + (vueInstance.$vnode.componentOptions.tag ? `::${vueInstance.$vnode.componentOptions.tag}` : "");
  // 找到keep-alive实例里的cache 和 keys集合
  let cache = vueInstance.$vnode.parent.componentInstance.cache;
  let keys = vueInstance.$vnode.parent.componentInstance.keys;
  // 如果找到当前组件实例的缓存,就destory销毁实例、删除cache、删除key
  if (cache[key]) {
    vueInstance.$destroy();
    delete cache[key];
    let index = keys.indexOf(key);
    if (index > -1) {
      keys.splice(index, 1);
    }
  }
}

它的核心思想就是通过 vueInstance.$vnode.parent.componentInstance 获取到 keep-alive 的实例,然后清除你想清除的组件实例的 key 对应的 cache ,同时 destory 掉它。

定义好该方法之后,接下来就需要导航守卫 beforeRouteLeave 来配合了。即,在需要动态处理缓存的页面中使用路由守卫 beforeRouteLeave ,根据即将要去的页面来判断是否要清除 keep-alive 缓存即可。

比如,就拿上面的例子来讲,我在列表页定义 beforeRouteLeave,在其中判断如果要去详情页,就不清除缓存,其余情况都要清除缓存。

// 判断要去的页面不是/detail页,就都应该删除keep-alive的缓存状态
beforeRouteLeave(to, from, next) {
  if(to.path !== '/detail'){
    removeKeepAliveCacheForVueInstance(this)
  }
  next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant