当前位置:网站首页>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')
}
}
边栏推荐
- Openlayers customize bubble boxes and navigate to bubble boxes
- APK签名流程介绍[通俗易懂]
- 线上开通ETF基金账户安全吗?有哪些步骤?
- MES production equipment manufacturing execution system software
- Intelligent operation and maintenance practice: banking business process and single transaction tracking
- Domestic spot silver should be understood
- [PHP foundation] realize the connection between PHP and SQL database
- Irradiance, Joule energy, exercise habits
- Product service, operation characteristics
- Replace UUID, nanoid is faster and safer!
猜你喜欢
Definition of rotation axis in mujoco
[beauty detection artifact] come on, please show your unique skill (is this beauty worthy of the audience?)
How to use JMeter function and mockjs function in metersphere interface test
This is the latest opportunity of the London bank trend
Penetration practice vulnhub range Keyring
Domestic spot silver should be understood
Samba basic usage
Fix the black screen caused by iPhone system failure
(16) ADC conversion experiment
Record 3 - the state machine realizes key control and measures the number of external pulses
随机推荐
开发那些事儿:EasyCVR平台添加播放地址鉴权
Session layer of csframework, server and client (1)
[beauty detection artifact] come on, please show your unique skill (is this beauty worthy of the audience?)
An example of data analysis of an old swatch and an old hard disk disassembly and assembly combined with the sensor of an electromagnetic press
The latest intelligent factory MES management system software solution
Development cost of smart factory management system software platform
New 95 community system whole station source code
ArrayList扩容详解
Check log4j problems using stain analysis
网上股票开户安全吗?是否可靠?
How to retrieve the password for opening Excel files
February 16, 2022 Daily: graph neural network self training method under distribution and migration
Detailed explanation of ArrayList expansion
ZABBIX alarm execute remote command
Debiasing word embeddings | talking about word embedding and deviation removal # yyds dry goods inventory #
The difference and relationship between iteratible objects, iterators and generators
Glidefast consulting was selected as the elite partner of servicenow in 2022
[2. Basics of Delphi grammar] 4 Object Pascal operators and expressions
Develop those things: easycvr cluster device management page function display optimization
MySQL + JSON = King fried