linux做网站好,最专业的网站建设组织,php网站识别手机,网站搭建排名优化keep-alive
1、目的
在使用组件时#xff0c;有时我们需要将组件进行缓存#xff0c;而不是重新渲染#xff0c;用以提高性能#xff0c;避免重复加载DOM#xff0c;提升用户的体验#xff1b; keep-alive 组件可以做到这一点#xff0c;它允许你缓存组件实例#xf…keep-alive
1、目的
在使用组件时有时我们需要将组件进行缓存而不是重新渲染用以提高性能避免重复加载DOM提升用户的体验 keep-alive 组件可以做到这一点它允许你缓存组件实例而不是销毁它们并在需要的时候重新使用它们。
2、作用
keep-alive 组件允许你缓存组件实例而不是销毁它们并在需要的时候重新使用它们。这可以提高性能避免重复加载DOM提升用户的体验。 比如
params currentView :当前活跃的组件名称
keep-alive!-- 动态组件 --component :iscurrentView/component
/keep-alive3、用法
keep-alive 在vue3中接收三个参数 include一个字符串或正则表达式数组包含才会缓存该组件用于匹配 需要 缓存的组件名称或组件实例。
exclude一个字符串或正则表达式数组不包含当前组件才会缓存即用于匹配 不需要 缓存的组件名称或组件实例。 max一个数字用于限制缓存的组件实例的数量。当达到这个数值时会自动将最不活跃的组件销毁以保证最大组件实例数量即执行类似数组的push操作进行先进先出的缓存策略 比如在app.vue 文件中
keep-aliverouter-view/router-view
/keep-alivetemplate
!-- 不缓存 Header,Footer 组件--keep-alive excludeHeader,Footer :max3component :iscurrentView/component/keep-alive!-- 缓存 Header,Footer 组件--keep-alive includeHeader,Footercomponent :iscurrentView/component/keep-alive!-- 使用正则表达式缓存 Header,Footer 组件 --keep-alive include/Header|Footer/component :iscurrentView/component/keep-alive!-- 使用数组缓存 Header,Footer 组件 --keep-alive include[Header, Footer]component :iscurrentView/component/keep-alive
/template注意 由于vue组合式api 中没有显性的进行组件名称命名(name),故使用 script setup 的单文件组件会自动根据文件名生成对应的 name 选项无需再手动声明 而在 选项式api中需要显性命名 如
scriptexport default{name: Header // 组件名称}
/script4、执行生命周期
keep-alive 组件的生命周期 1、组件第一次进入即没有被缓存的时候会执行 setup()、 onBeforeMount() 、onMounted()、onActivated() (没有keep-alive时候首次执行setup()、 onBeforeMount() 、onMounted()) 2、组件被缓存的时候会执行onActivated() 3、组件被激活的时候会执行onActivated() 4、组件被移除的时候会执行onDeactivated() 下图
5、执行原理
……function pruneCache(filter?: (name: string) boolean) {cache.forEach((vnode, key) {const name getComponentName(vnode.type as ConcreteComponent)if (name (!filter || !filter(name))) {// 当前缓存的组件名称 和 当前活跃的组件名称不相同则移除该组件pruneCacheEntry(key)}})}function pruneCacheEntry(key: CacheKey) {const cached cache.get(key) as VNodeif (!current || !isSameVNodeType(cached, current)) {// 卸载unmount(cached)} else if (current) {// current active instance should no longer be kept-alive.// we cant unmount it now but it might be later, so reset its flag now.// 重新设置缓存标识resetShapeFlag(current)}cache.delete(key)keys.delete(key)}// prune cache on include/exclude prop change// 观测 include | exclude 的值变化并且能观测到更新后的DOM进行缓存更新watch(() [props.include, props.exclude],([include, exclude]) {include pruneCache(name matches(include, name))exclude pruneCache(name !matches(exclude, name))},// prune post-render after current has been updated{ flush: post, deep: true },)……// 判断是否达到最大缓存数量if (max keys.size parseInt(max as string, 10)) {pruneCacheEntry(keys.values().next().value)}
……在vue3 中keep-alive 使用 cache 一个 Map 对象key 是组件名称value 是组件实例通过缓存组件实例避免重复加载DOM提升用户体验。 而在vue2 中keep-alive 使用 cache 一个 Object 对象相比较Map 对象性能更好
仅代表个人观点如有错误欢迎批评指正