您的位置:首页 > 游戏 > 游戏 > 上网管理系统_智慧团建官网网页版入口_app地推接单平台有哪些_2023年6月份又封城了

上网管理系统_智慧团建官网网页版入口_app地推接单平台有哪些_2023年6月份又封城了

2025/7/1 14:53:36 来源:https://blog.csdn.net/m0_62008199/article/details/142585644  浏览:    关键词:上网管理系统_智慧团建官网网页版入口_app地推接单平台有哪些_2023年6月份又封城了
上网管理系统_智慧团建官网网页版入口_app地推接单平台有哪些_2023年6月份又封城了

vue3中< keep-alive >页面实现缓存及遇到的问题

实现原理:keep-alive 是 Vue 的内置组件,当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。实现不同路由是否缓存只需要设置对应路由参数keepAlive为true,不需要缓存的路由设置false。如果是多级路由你要设置子路由缓存的话,它的父级路由的keepAlive也必须为true。

keep-alive的参数
参数原理
include它会根据组件的 name 选项进行匹配,所以组件如果想要条件性地被 KeepAlive 缓存,就必须显式声明一个 name 选项
exclude任何名称与 exclude 匹配的组件都不会被缓存
max最大缓存实例数
<!-- 以英文逗号分隔的字符串 -->
<KeepAlive include="a,b"><component :is="view" />
</KeepAlive><!-- 正则表达式 (需使用 `v-bind`) -->
<KeepAlive :include="/a|b/"><component :is="view" />
</KeepAlive><!-- 数组 (需使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']"><component :is="view" />
</KeepAlive>
一:keep-alive设置缓存
<template><div id="app"><!--需要缓存的keep-alive配置 展示内容--><keep-alive :include="getKeepAliveNames"><router-view v-if="$route.meta.keepAlive" /></keep-alive><!--不需要缓存的keep-alive 配置 展示内容--><router-view v-if="!$route.meta.keepAlive" /></div>
</template>
二:router,多级router页面缓存
  //首页{path: "/home",name: "home",component: component: () => import("@/views/home/index.vue")//配置keep-alive 的状态  meta: {keepAlive: true, //需要缓存的页面,title:"首页"},},{path: "/user",name: "user",component:  component: () => import("@/views/user/index.vue"),//配置keep-alive 的状态  meta: {keepAlive: true, //需要缓存的页面title:"用户"},children:[{path: "/userOne",name: "userOne",component:  component: () => import("@/views/userOne/index.vue"),//配置keep-alive 的状态  meta: {keepAlive: true, //需要缓存的页面,title:"用户1"},},{path: "/userTwo",name: "userTwo",component:  component: () => import("@/views/userTwo/index.vue"),//配置keep-alive 的状态  meta: {keepAlive: true, //需要缓存的页面,title:"用户2"},},]},
三:查看页面是否缓存成功
1:查看 onActivated ,onDeactivated 判断 keepalive是否生效
<script setup>
import { onActivated, onDeactivated } from 'vue'onActivated(() => {// 调用时机为首次挂载// 以及每次从缓存中被重新插入时
})onDeactivated(() => {// 在从 DOM 上移除、进入缓存// 以及组件卸载时调用
})
</script>
2:使用vue插件判断缓存是否生效

在这里插入图片描述

四:遇到的问题

写了以上步骤缓存都失效,查看了原因:是因为keep-alive里面的名称和组件的名称没有匹配上。
解决办法是在组件页面给他命名,这样就解决了。

import { defineOptions} from 'vue';
defineOptions({ name: 'userRegister' })//与路由的name要一致

如果遇到defineOptions报错
更新vue和vue-router版本就行;我的版本是:"vue": "3.3.4","vue-router": "^4.0.12",然后再npm i安装一下再重启项目就可以了。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com