外观
页面缓存
页面缓存
介绍
在 Vue3 中,页面缓存是一种优化技术,用于保留组件的状态并避免重复渲染,从而提升应用的性能和用户体验。主要通过内置组件 <KeepAlive>
和相关 API 实现。
- 缓存被包裹的组件实例,而非销毁它们,在组件切换时保留状态。
- 常用于频繁切换的路由组件(如 Tab 页)或动态组件。
多标签页
标签页使用的是 keep-alive
和 router-view
实现,实现切换 tab
后还能保存切换之前的状态。
开启缓存有 2 个条件
- 路由设置
name
,且不能重复 - 路由对应的组件加上
name
,与路由设置的name
保持一致
静态路由页面缓存
开启页面缓存示例
- 文件:
src\router\modules\remaining.ts
,定义个人中心静态路由设置name
ts
{
path: '/user',
component: Layout,
name: 'UserInfo',
meta: {
hidden: true
},
children: [
{
path: 'profile',
component: () => import('@/views/Profile/Index.vue'),
name: 'Profile',
meta: {
canTo: true,
hidden: true,
noTagsView: false,
icon: 'ep:user',
title: t('common.profile')
}
},
{
path: 'notify-message',
component: () => import('@/views/system/notify/my/index.vue'),
name: 'MyNotifyMessage',
meta: {
canTo: true,
hidden: true,
noTagsView: false,
icon: 'ep:message',
title: '我的站内信'
}
}
]
},
- 文件:
src\views\Profile\Index.vue
,个人中心页面组件的name
定义
vue
<script lang="ts" setup>
import { BasicInfo, ProfileUser, ResetPwd } from './components'
// import { BasicInfo, ProfileUser, ResetPwd, UserSocial } from './components'
const { t } = useI18n()
defineOptions({ name: 'Profile' })
const activeName = ref('basicInfo')
</script>
关闭页面缓存示例:可以将 noCache
配置成 true
即可关闭缓存或者组件不添加 name
属性。
ts
{
path: 'workplace',
component: () => import('@/views/Dashboard/Workplace.vue'),
name: 'Workplace',
meta: {
title: t('router.workplace'),
noCache: true
}
}
动态路由页面缓存
开启页面缓存示例
菜单管理——添加菜单
- 组件名字:与页面组件中定义的一样
- 缓存状态:缓存
页面组件
src\views\system\user\index.vue
中name设置一样