Vue项目中keepAlive的使用说明(超级实用版)
作者:鲁智深拳打陈冠希 时间:2024-05-02 16:34:02
keepAlive的使用
在开发的过程中如果碰到经常浏览需要缓存的页面,而且页面很长需要记录滚动的位置这时就需要用到keepAlive。
一共有三个步骤
1、首先在路由中的mate属性中记录keepAlive,如果需要缓存则置为true。
path:'/index',
name:''index',
component:()=>import('../../index/index'),
meta:{keepAlive:true}
2、在创建router实例的时候加上scrollBehavior方法(keepAlive才会生效)。
let router=new Router({
? ? mode:"hash",//1、hash哈希:有#号。2、history历史:没有#号
? ? base:process.env.BASE_URL, //自动获取根目录路径
? ? scrollBehavior:(to,from,position)=>{
? ? ? ? if(position){
? ? ? ? ? ? return position
? ? ? ? }else{
? ? ? ? ? ? return {x:0,y:0}
? ? ? ? }
? ? },
3、需要缓存的router-view包上keep-alive(要有两个router-view,一个是缓存的时候显示,一个是不缓存的时候显示,有的时候不需要缓存)。
<keep-alive>
?? ?<router-view v-if="$router.meta.keepAlive"></router-view>
</keep-alive>
?? ?<router-view v-if="!$router.meta.keepAlive"></router-view>
注意
在keep-alive中的组件会有两个生命周期的钩子函数,activated和deactivated,其中activated是在组件第一次渲染时会被调用,而且之后每次缓存组件被激活都会被调用。所以一般使用时需要里面的代码和created函数中的代码一样即可。
keepAlive的注意事项
问题描述
今天在测试提到了一个bug,当重复进入相同的组建的时候,mounted和created内的方法不触发,导致页面展示不一样
原因
<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。(所以不会触发mounted和created事件钩子)
当组件在 <keep-alive> 内被切换,它的 activated (激活)和 deactivated (不激活)这两个生命周期钩子函数将会被对应执行。
include and exclude
include (缓存的文件)和 exclude(不换存文件) 属性允许组件有条件地缓存。
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
? <component :is="view"></component>
</keep-alive>
?
<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
? <component :is="view"></component>
</keep-alive>
?
<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
? <component :is="view"></component>
</keep-alive>
max
最多可以缓存多少组件实例。
<keep-alive :max="10">
? <component :is="view"></component>
</keep-alive>
来源:https://blog.csdn.net/qq_41983641/article/details/113368703
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL数据库如何导入导出(备份还原)
![](https://img.aspxhome.com/file/2023/4/74854_0s.jpg)
ElasticSearch核心概念
![](https://img.aspxhome.com/file/2023/4/114694_0s.png)
关于Python中的if __name__ == __main__详情
![](https://img.aspxhome.com/file/2023/2/127322_0s.png)
ASP验证码的实现原理及源码
非常酷炫的Bootstrap图片轮播动画
![](https://img.aspxhome.com/file/2023/4/135594_0s.jpg)
Laravel框架实现利用监听器进行sql语句记录功能
Python创建模块及模块导入的方法
详解Python 正则表达式模块
![](https://img.aspxhome.com/file/2023/8/109328_0s.png)
python绘制铅球的运行轨迹代码分享
![](https://img.aspxhome.com/file/2023/3/84123_0s.jpg)
Javascript特效--划过放大的列表
![](https://img.aspxhome.com/file/UploadPic/20083/21/2008321122917663s.jpg)
Python如何在终端彩色打印输出
![](https://img.aspxhome.com/file/2023/9/82619_0s.png)
制作Python数字华容道的实现(可选择关卡)
![](https://img.aspxhome.com/file/2023/5/100805_0s.png)
Go语言图片处理和生成缩略图的方法
使用Protocol Buffers的C语言拓展提速Python程序的示例
Python使用sklearn库实现的各种分类算法简单应用小结
python采用django框架实现支付宝即时到帐接口
一篇文章彻底弄懂Python字符编码
Python中计算三角函数之cos()方法的使用简介
保护SQL服务器的安全 用户识别问题
![](https://img.aspxhome.com/file/UploadPic/200812/20081225122629996.jpg)
php中加密解密DES类的简单使用方法示例
![](https://img.aspxhome.com/file/2023/3/554131_0s.png)