vc-keep-alive

优化了keepAlive的缓存机制, 可以像APP那样前进刷新, 返回销毁

Usage no npm install needed!

<script type="module">
  import vcKeepAlive from 'https://cdn.skypack.dev/vc-keep-alive';
</script>

README

vc-keep-alive

线上 Demo

改变了keepAlive的缓存机制, 可以像 APP 那样前进重建, 返回销毁
不过目前仅仅用于Page级别, 也就是一级路由, 其他级路由似乎没有需要
原本的keepAlive默认是以componentName来做缓存的 key
当然如果有vnode.key的话则会使用vnode.key, 所以网上很多通过$route.fullPath当作 key
可以实现params/query的变更新建组件, 但是无法做到返回销毁
如果使用$destroy()去手动销毁, 但是keepAlive里面还是存在缓存标记
导致从 3 级路由返回到 2 级路由时拿缓存的instance是失效的, 进而导致重建
所以通过Page前进返回行为分析, 总结出 key 的生成规则

解决的痛点

  1. 子路由的更新和父级路由无关, 所以一级路由的缓存 key 是命中路由的父一级路由相关, 目前是父路由的 path + 父子路由相同的 params
  2. 还有就是自己功能性路由的支持
    1. 比如使用支持返回键的 imgsViewer, 需要 history 压栈而不触发 forward/backward 事件, 所以提供了 ignorePaths 参数
    1. 比如子路由不适用 router-view 来渲染, 而是使用 view-pager 来自行控制, 支持左右滑动切换, 如果 view-pager 的页面状态是需要保存到 url, 则需要一级路由的一个动态路由占位符, 充当子路由, 所以提供了 ignoreParams 参数

使用

npm install vc-keep-alive
<template>
  <div id="app" :class="pageAct">
    <transition name="page-slide">
      <vc-keep-alive
        :ignorePaths="ignorePaths"
        :ignoreParams="ignoreParams"
        @init="log('init', $event);"
        @forward="log('forward', $event);"
        @replace="log('replace', $event);"
        @backward="log('backward', $event);"
      >
        <router-view />
      </vc-keep-alive>
    </transition>
  </div>
</template>

<script>
import Vue from 'vue';
import VcKeepAlive from 'vc-keep-alive';

Vue.use(VcKeepAlive);

export default {
  data() {
    return {
      pageAct: '',
      ignorePaths: ['popup='],
      ignoreParams: ['pagerTab']
    };
  },

  methods: {
    log(act, args) {
      console.log(act, args);
      this.pageAct = 'page-' + act;
    }
  }
};
</script>