vue3 keepalive router-view 頁面緩存的相關問題


1、頁面切換 不觸發 activated 生命周期

代碼如下

<template>
<!-- include 可以用逗號分隔字符串、正則表達式或一個數組來表示 -->
  <router-view v-slot="{ Component }">
    <keep-alive :include="cacheViews">
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from 'vue'
import { useStore } from 'vuex'

export default defineComponent({
  name: 'APP',
  setup() {
    const store = useStore()
    const cacheViews = computed(() => store.state.app.cachedViews)   // store.state.app.cachedViews 是 需要緩存的 路由組件name 的數組
     // const cacheViews = computed(() => store.state.app.cachedViews.join(',')) // 逗號分隔字符串模式 

    return {
      cacheViews
    }
  }
})
</script>

頁面表現: 頁面能正常切換,但是不觸發activated deactivated 生命周期

原因: store.state.app.cachedViews 返回的是一個 Proxy, 代理了數組,並不是數組本身

修改:將 的 cacheViews 數組模式改為 逗號分隔字符串模式 就正常了
即: const cacheViews = computed(() => store.state.app.cachedViews.join(','))

2、keep-alive include 屬性如果是個空字符串,則所有的頁面都會被緩存

上面代碼中,如果 cacheViews 數組為空數組,則 store.state.app.cachedViews.join(',') 返回的就是空字符串,造成所有頁面被緩存,導致結果不符需求。

所以改成:

 const cacheViews = computed(() => store.state.app.cachedViews.concat([]))

參考:
https://v3.cn.vuejs.org/api/built-in-components.html#keep-alive
https://next.router.vuejs.org/zh/guide/migration/#router-view-、-keep-alive-和-transition


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM