Vue3实现页面缓存支持刷新当前页面

655 阅读1分钟

由路由配合KeepAlive组件实现。

缓存页面默认最多保持十个,通过 include 属性来实现动态缓存当前导航中对应的页面。

其中组件 key 保证同一个页面组件不同实例的信息更新,比如编辑详情A与详情B。

template

<router-view #default="{ Component }">

  <keep-alive :include="keepAliveViews">

    <component :is="Component" :key="routeKey" v-if="isMounted" />

  </keep-alive>

</router-view>

动态更新需要缓存的页面   

通过isMounted以及keepAlive include属性的更新实现手动清除keep-alive中的缓存,并再次缓存。


const headerTabStore = useHeaderTabsStore()

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

watch(

  () => headerTabStore.tabList,

  (newTabList) => {

    const comps: string[] = []

    newTabList.forEach((tab) => {

      if (tab.meta.componentName) {

        comps.push(tab.meta.componentName as string)

      }

    })

    keepAliveViews.value = comps

  }

)

支持只刷新当前页面

const isMounted = ref(true)

const refreshCurrentPage = (tab: Tab) => {

  if (tab.meta.componentName !== undefined) {

    isMounted.value = false

    keepAliveViews.value = keepAliveViews.value.filter(

      (name) => name !== tab.meta.componentName

    )

    nextTick(() => {

      isMounted.value = true

      keepAliveViews.value = keepAliveViews.value.concat(

        tab.meta.componentName as string

      )

    })

  }

}

每一个路由对应一个页面组件,需要在路由 meta 里面声明componentName与组件名称保持一致,不声明则不会进行缓存

{

    path: 'xxx',

    name: 'xxxxxx',

    meta: {

      componentName: 'YourComponent'

    },

    component: () => import('@/YourComponent.vue')

  },