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