当前位置:网站首页>Vue uses keep alive to cache page optimization projects
Vue uses keep alive to cache page optimization projects
2022-07-01 18:15:00 【Sen yuan】
Concept
keep-alive yes Vue Built in components of , When it wraps dynamic components , An inactive component instance is cached , Instead of destroying them . and transition be similar ,keep-alive It's an abstract component : It doesn't render itself as a DOM Elements , It also doesn't appear in the parent component chain .
effect
During component switching Keep the switched components in memory , Prevent duplicate rendering DOM, Reduce loading time and performance consumption , Improve user experience
principle
stay created Hook function call will need to cache VNode The node is saved in this.cache in / stay render( Page rendering ) when , If VNode Of name Meet cache conditions ( It can be used include as well as exclude control ), Will follow this.cache Take out the previously cached VNode Instance rendering .
VNode: fictitious DOM, It's really just a JS object
Parameters (Props)
- include - String or regular expression . Only components with matching names will be cached .
- exclude - String or regular expression . Any component with a matching name will not be cached .
- max - Numbers . How many component instances can be cached at most
For life cycle function changes
Be included in keep-alive Components created in , There will be two more life cycle hooks : activated And deactivated
\1. activated
stay keep-alive Called when the component is activated
\2. deactivated
stay keep-alive Call... When the component leaves
Normal life cycle :beforeRouteEnter --> created --> mounted --> updated -->destroyed
Use keepAlive Post life cycle :
Enter the cache page for the first time :beforeRouteEnter --> created --> mounted --> activated --> deactivated
Go to the cache page again :beforeRouteEnter --> activated --> deactivated
notes :
1、 there activated Very useful , Because when a page is cached ,created,mounted And so on , If you want to do something , So it can be activated Finish in ( Here's a chestnut : The list page goes back to where it was last viewed )
2、activated keep-alive Called when the component is activated , This hook is not called during server-side rendering .
3、deactivated keep-alive Called when the component is disabled , This hook is not called during server-side rendering .
Cache entire project
stay App.vue Inside
If you need to cache the entire project , Set as follows ( Direct wrapping root router-view that will do ):
<template>
<div id="app">
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template> Use keepAlive What changes have taken place in the post life cycle
<script>
export default {
name: 'App'
}
</script>
combination Router, Cache some pages
1、 stay App.vue Set in :( Switch the mode according to whether the cache is needed )
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
2、 stay router.js Routing page settings :
new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home,
redirect: 'goods',
children: [
{
path: 'goods',
name: 'goods',
component: Goods,
meta: {
keepAlive: false // No need to cache
}
},
{
path: 'ratings',
name: 'ratings',
component: Ratings,
meta: {
keepAlive: true // Cache required
}
},
{
path: 'seller',
name: 'seller',
component: Seller,
meta: {
keepAlive: true // Cache required
}
}
]
}
]
})
notes :
Configured with keepAlive The page of , No re rendering on re-entry , Similarly, the components in this page will not be rendered again . This may lead to related operations within the component ( Those operations that need to re render the page every time : Such as value transfer between parent and child components ) No longer valid . This may lead to some inexplicable and unverifiable bug
Use the new attribute include/exclude, Cache some pages
vue2.1.0 Added include,exclude Two properties , Allow components to cache conditionally . Both can be comma separated strings 、 Regular expressions or an array to represent .
<!-- Comma separated strings -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
<!-- Regular expressions ( need `v-bind` binding ) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
<!-- Array ( need `v-bind` binding ) -->
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>
notes : Match first checks the component's own name Options , If name Option not available , Then match its local registration name ( Parent component components Key value of option ). Anonymous components cannot be matched .
Dynamic judgment , Use v-bind:include
<keep-alive :include="includedComponents">
<router-view></router-view>
</keep-alive>
includedComponents Dynamic setting is enough
Use beforeRouteLeave perhaps afterEach In the process of interception
For example, in the project Category Settings in the component :
beforeRouteLeave(to,from,next){
if(to.name=='DemoIndex'){
if(!from.meta.keepAlive){
from.meta.keepAlive=true
}
next()
}else{
from.meta.keepAlive=false
to.meta.keepAlive=false
next()
}
},
stay beforeRouteLeave in to.name Set the dynamic cache according to the specific route .
The list page goes back to where it was last viewed
Conditions :1、 List pages cannot use lazy loading to delay loading data ,2、 The list page needs to use keepAlive cache
beforeRouteLeave(to,from,next){
// Store the height in... Before leaving the page sessionStorage. It is not recommended to use localStorage, because session It will be cleared automatically when the browser is closed , and local It needs to be cleared manually , A little bit of a problem .
sessionStorage.setItem('scrollH',document.getElementById('demo').scrollTop)
next()
},
activated(){
// stay activated In the life cycle , from sessionStorage Read the height value in and set it to dom
if(sessionStorage.getItem('scrollH')){
document.getElementById('demo').scrollTop=sessionStorage.getItem('scrollH')
}
}
边栏推荐
- Development cost of smart factory management system software platform
- Irradiance, Joule energy, exercise habits
- . Net cloud native architect training camp (permission system code implements actionaccess) -- learning notes
- [beauty detection artifact] come on, please show your unique skill (is this beauty worthy of the audience?)
- Penetration practice vulnhub range Keyring
- [2. Basics of Delphi grammar] 4 Object Pascal operators and expressions
- Develop those things: easycvr cluster device management page function display optimization
- Extract the compressed package file and retrieve the password
- Fix the black screen caused by iPhone system failure
- Is online stock account opening safe? Is it reliable?
猜你喜欢

Yolov5 practice: teach object detection by hand

Countdownlatch blocking wait for multithreading concurrency

Penetration practice vulnhub range Tornado

Kia recalls some K3 new energy with potential safety hazards
![[PHP foundation] realize the connection between PHP and SQL database](/img/eb/c8953eddfe3b19b0adb5529957d275.jpg)
[PHP foundation] realize the connection between PHP and SQL database

Highly reliable program storage and startup control system based on anti fuse FPGA and QSPI flash

Good looking UI mall source code has been scanned, no back door, no encryption

Oracle TRUNC function processing date format

Cloud picture says | distributed transaction management DTM: the little helper behind "buy buy buy"

The new server is packaged with the source code of H5 mall with an operation level value of several thousand
随机推荐
Relationship between sensor size, pixel, dpi resolution, inch and millimeter
Easycvr accesses the equipment through the national standard gb28181 protocol. What is the reason for the automatic streaming of the equipment?
证券开户安全么,有没有什么样的危险呢
线上开通ETF基金账户安全吗?有哪些步骤?
Detailed explanation of ArrayList expansion
Bug of QQ browser article comment: the commentator is wrong
Session layer of csframework, server and client (1)
Blackwich: the roadmap of decarbonization is the first step to realize the equitable energy transformation in Asia
js如何将带有分割符的字符串转化成一个n维数组
Is it reasonable and safe to open a securities account for 10000 shares free of charge? How to say
Pytorch crossentropyloss learning
Intelligent operation and maintenance practice: banking business process and single transaction tracking
[beauty detection artifact] come on, please show your unique skill (is this beauty worthy of the audience?)
Extract the compressed package file and retrieve the password
Fix the problem that easycvr device video cannot be played
Penetration practice vulnhub range Keyring
Zabbix报警执行远程命令
ACL 2022 | decomposed meta learning small sample named entity recognition
网上股票开户安全吗?是否可靠?
Reflective XSS vulnerability