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, 代理了數組,並不是數組本身
修改:將
即: 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
