溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue3嵌套路由中怎么使用keep-alive緩存多層

發(fā)布時(shí)間:2023-04-18 09:49:08 來(lái)源:億速云 閱讀:244 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容主要講解“Vue3嵌套路由中怎么使用keep-alive緩存多層”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Vue3嵌套路由中怎么使用keep-alive緩存多層”吧!

前言

keep-alive是Vue中的緩存標(biāo)簽, 組件在標(biāo)簽中的內(nèi)容會(huì)被緩存下來(lái);但是在多層嵌套的router-view中, 只能緩存到該層下的router-view, 由于路由嵌套比較常見(jiàn),所以這里提供兩種我覺(jué)得OK的解決方案。

解決思路

  • 路由層級(jí)扁平化,在路由守衛(wèi)中執(zhí)行一個(gè)拍平的函數(shù),將需要緩存的路由提升到第一層,這樣處理會(huì)影響到路由層級(jí),最直白的影響如對(duì) 面包屑 等功能有直接影響

  • 把所有的 router-view 都通過(guò) keep-alive 包裹起來(lái), 通過(guò)keep-aliveinclude, exclude 來(lái)判斷是否需要緩存。

Demo項(xiàng)目結(jié)構(gòu)

router.ts

Vue3嵌套路由中怎么使用keep-alive緩存多層

路由的結(jié)構(gòu)大概是這樣的 Layout > TableManage > (List, Detail, Add...)

路由層級(jí)扁平化

在路由的 afterEach 執(zhí)行一個(gè)扁平化方法, 舉例:

import router from '@/router/index'
import PageTitleUtils from '@/utils/PageTitleUtils'
import { ElMessage } from 'element-plus'
import useStore from '@/store/index'
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const { user, routeStore } = useStore()

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start()
  if (user.hasToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (user.hasUserInfo()) {
        next()
        NProgress.done()
      } else {
        try {
          await user.getUserInfo()
          await routeStore.setRoutes()
          next({ ...to, replace: true })
          NProgress.done()
        } catch (error: any) {
          routeStore.resetRoutes()
          user.resetUserInfo()
          ElMessage.error(error || 'Has Error')
          next(`/login?redirect=${to.fullPath}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
      NProgress.done()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach((to: any) => {
  NProgress.done()
  // set page title
  const { meta }: any = to
  document.title = PageTitleUtils.getPageTitle(meta.title)
  // delayering router
  delayeringRoute(to)
})


/**
 * 遞歸處理多余的 layout : <router-view>,
 * 讓需要訪問(wèn)的組件保持在第一層 index : <router-view> 之下
 */
function delayeringRoute(to: RouteLocationNormalized) {
  if (to.matched && to.matched.length > 2) {
    for (let i = 0; i < to.matched.length; i++) {
      const element = to.matched[i]
      // 移除多余的 layout, 也許你項(xiàng)目中并不叫 layout ,自行修改此處
      if (element.components?.default.name === 'layout') {
        to.matched.splice(i, 1)
        handleKeepAlive(to)
      }
    }
  }
}

以上代碼示例中, delayeringRoute 是移除多余 layout 的方法, 在路由的afterEach方法中去移除,弊端很明顯, 路由的結(jié)構(gòu)受到了影響

給所有的 router-view 都嵌套上 keep-alive

這是我比較推薦的一種方法, 沒(méi)什么副作用,也不麻煩, 畢竟所有的 router-view 都一樣,如果你使用的IDE是vscode,可以直接把這段代碼寫(xiě)進(jìn)項(xiàng)目中的代碼片段, 方便使用。

Layout的Main

<script lang="ts" setup name="AppMain">
  import { useRoute } from 'vue-router'
  import useStore from '@/store';
  import { storeToRefs } from 'pinia';

  const route = useRoute()
  const { tagview } = useStore()
  const { cacheList } = storeToRefs(tagview)
</script>

<template>
  <div class="app-main">
    <router-view v-slot="{ Component }">
      <keep-alive :include="cacheList">
        <component :is="Component" :key="route.fullPath" />
      </keep-alive>
    </router-view>
  </div>
</template>

<style scoped lang="scss">
</style>

其他嵌套的路由, 不管幾層,都可以這樣處理

<script lang="ts" setup name="TableManage">
  import { useRoute } from 'vue-router'
  import useStore from '@/store';
  import { storeToRefs } from 'pinia';
  import { onMounted } from 'vue';

  const route = useRoute()
  const { tagview } = useStore()
  const { cacheList } = storeToRefs(tagview)

  onMounted(() => {
    tagview.addCacheList('TableManage')
  })

</script>

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="cacheList">
      <component :is="Component" :key="route.fullPath" />
    </keep-alive>
  </router-view>
</template>

這樣就可以實(shí)現(xiàn)嵌套路由的緩存了。

到此,相信大家對(duì)“Vue3嵌套路由中怎么使用keep-alive緩存多層”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI