vue3 实现keepalive includes 缓存

import { ref, nextTick } from 'vue'

const caches = ref<string[]>([])

export default function useRouteCache () {
  // 添加缓存的路由组件
  function addCache (componentName: string | string []) {
    if (Array.isArray(componentName)) {
      componentName.forEach(addCache)
      return
    }
    
    if (!componentName || caches.value.includes(componentName)) return

    caches.value.push(componentName)
  }

  // 移除缓存的路由组件
  function removeCache (componentName: string) {
    const index = caches.value.indexOf(componentName)
    if (index > -1) {
      return caches.value.splice(index, 1)
    }
  }
  
  // 移除缓存的路由组件的实例
  async function removeCacheEntry (componentName: string) {    
    if (removeCache(componentName)) {
      await nextTick()
      addCache(componentName)
    }
  }
  
  return {
    caches,
    addCache,
    removeCache,
    removeCacheEntry
  }
}

使用

<router-view v-slot="{ Component }">
  <keep-alive :include="caches">
    <component :is="Component" />
  </keep-alive>
</router-view>

<script setup lang="ts">
import useRouteCache from './hooks/useRouteCache'
const { caches, addCache , removeCacheEntry } = useRouteCache()

addCache(['List'])
removeCacheEntry('List')

在路由跳转前去清除路由

<router-link to="/list" @click="removeCacheBeforeEnter">列表页</router-link>
function removeCacheBeforeEnter () {
  removeCacheEntry('List') //省略导入 hook 的代码
}
这种适合一种需求
在首页点击跳转列表页前,在点击事件时去清除列表页缓存,这样的话在首页和列表页如果用浏览器的前进后退来回切换,列表页都是缓存状态,只要当重新点击跳转链接的时候,才重新加载列表页。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容