当前位置:网站首页>keep-alive
keep-alive
2022-06-25 10:35:00 【m0_ forty-nine million four hundred and seventy-one thousand si】
1. brief introduction
keep-alive yes Vue Of Built in components , When it The parcel Dynamic component , Meeting cache Inactive component instances , instead of The destruction they .
and transition be similar ,keep-alive It's a Abstract components : It doesn't render itself as a DOM Elements , It also doesn't appear in the parent component chain .
effect : During the component switching process state Retain In memory , prevent Repeat rendering DOM, Reduce Load time and performance consumption , Improve User experience .
principle : stay created Function calls will need to be cached VNode node preservation stay this.cache in
stay render( Page rendering ) when , If VNode Of name accord with 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 )
2. Use
2.1 Parameters
Parameter name value describe
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 .
Be careful : include/exclude The value is in the component name name , Instead of components in the route name name ;
// router.js
{
path: '/home',
name: 'home',
component: () => import('../views/home.vue')
},
{
path: '/test',
name: 'test',
component: () => import('../views/test.vue')
},
// App.vue
<keep-alive include="test">
<router-view/>
</keep-alive>
----------------------------------------------------------------------------------------------------------------
Add : include/exclude Multiple forms of values .
// 1. Will cache name by test The components of ( basic )
<keep-alive include='test'>
<router-view/>
</keep-alive>
// 2. Will cache name by a perhaps b The components of , Use with dynamic components
<keep-alive include='a,b'>
<router-view/>
</keep-alive>
// 3. Using regular expressions , Need to use v-bind
<keep-alive :include='/a|b/'>
<router-view/>
</keep-alive>
// 4. Dynamic judgment
<keep-alive :include='includedComponents'>
<router-view/>
</keep-alive>
// 5. Will not cache name by test The components of
<keep-alive exclude='test'>
<router-view/>
</keep-alive>
// 6. and `<transition>` Use it together
<transition>
<keep-alive>
<router-view/>
</keep-alive>
</transition>
// 7. Array ( Use `v-bind`)
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>
// test.vue
<template>
<div class="wrap">
<input type="text" v-model="inputVal">
</div>
</template>
<script>
export default {
name:'test',
data(){
return {
inputVal:'',
}
}
}
</script>
At this point, switch routes , We'll find out test In file inputVal Will be cached , and home The value in is not cached .
Besides , We can also use the... In the route meta Attribute to control , Whether cache is needed .
take test In the routing meta add to keepAlive The attribute is true, Indicates that the current routing component needs to be cached .
// router.js
{
path: '/home',
name: 'home',
component: () => import('../views/home.vue')
},
{
path: '/test',
name: 'test',
meta:{
keepAlive:true
},
component: () => import('../views/test.vue')
},
keep-alive Code can be combined with v-if Package , If meta Medium keepAlive by true Cache , No side does not cache .
In development , We can combine the route guard to implement the caching of components that need caching .
Portal :Vue Routing hook ( Navigation guard ) Detailed explanation and application scenarios
export default {
beforeRouteLeave(to, from, next) {
to.meta.keepAlive = true;
next();
}
}
</script>
.2 Life cycle function
name describe
activated stay keep-alive Called when the component is activated , The hook function is not called during server-side rendering .
deactivated stay keep-alive Called when the component is disabled , This hook is not called during server-side rendering .
Use < keep-alive > Will keep the data in memory , If you want to get the latest data every time you enter the page , Need to be in activated Stage acquisition data , Bear the original created The task of getting data in the hook .
Be included in < keep-alive > Components created in , There will be two more life cycle hooks : activated And deactivated
activated: Call when the component is activated , The component is also called the first time it is rendered , After each time keep-alive Called when activated .
deactivated: Call when the component is deactivated .
Be careful : Only components are keep-alive When wrapping , These two lifecycles are called , If used as a normal component , It won't be called , And in 2.1.0 After the version , Use exclude After exclusion , Even if it's wrapped in keep-alive in , These two hooks are still not called ! In addition, this hook will not be called when rendering on the server side .
When to get the data ?
When introducing keep-alive When , The first time the page enters , Trigger sequence of hook created -> mounted -> activated, Trigger on exit deactivated.
When you enter ( To move forward or backward ) when , Trigger only activated.
We know keep-alive After that, the first initialization of the page template resolves to HTML Fragment after , If you enter again, you will not be re parsing, but reading the data in memory .
Only when the data changes , Only use VirtualDOM Conduct diff to update . therefore , Page entry data acquisition should be in activated You can also put a portion of .
Data download finished, manual operation DOM The part of should also be in activated It will take effect only if it is implemented in the middle of the project .
therefore , should activated Leave a copy of the data acquisition code , Or not created part , Direct will created The code in is transferred to activated in .
2.3 Application scenarios
If not used keep-alive Components , The page will still be re rendered when the page goes back , Trigger created hook , The use experience is not good .
Use... In the following scenarios keep-alive Components can significantly improve the user experience , There is a multi-level relationship between menus ( Such as : Home page -> List of pp. -> Details page ) Scene :
When you jump to a list page from the home page , List page component re rendering ;
When returning to the list page from the details page , List page component cache Do not re request data ;
// app.vue
<template>
<div id="app">
<keep-alive :include="keepAliveInclude">
<router-view/>
</keep-alive>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
name:'home',
computed:{
...mapGetters([
'keepAliveInclude',
])
},
}
</script>
store Chinese vs keepAliveInclude Status update save
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// keepAlive Cache components
keepAliveInclude:[],
},
getters:{
keepAliveInclude: state => state.keepAliveInclude,
},
mutations: {
SET_KEEPALIVEINCLUDE:(state, keepAliveInclude) => {
state.keepAliveInclude = keepAliveInclude;
}
},
actions: {
setKeepAliveInclude({ commit }, keepAliveInclude){
commit("SET_KEEPALIVEINCLUDE", keepAliveInclude)
},
},
})
<template>
<div>
<button @click="goHome"> Home page </button>
<button @click="goDetail"> details </button>
list : <input type="text" v-model="inputVal">
</div>
</template>
<script>
export default {
name:'list',
data(){
return {
inputVal:'',
}
},
methods:{
goDetail(){
this.$router.push('./detail')
},
goHome(){
this.$router.push('./home')
}
},
beforeRouteLeave (to, from, next) {
if(to.name == 'detail'){
this.$store.dispatch('setKeepAliveInclude',['list'])
}else{
this.$store.dispatch('setKeepAliveInclude',[])
}
// next();
setTimeout(() => { next(); }, 10); // next() It needs to be wrapped with a timer , Otherwise, it cannot be cached after multiple switches
}
}
</script>
边栏推荐
- Flask blog practice - archiving and labeling of sidebar articles
- Think about it
- Flask blog practice - realize personal center and authority management
- 成长:如何深度思考与学习
- Unreal Engine graphics and text notes: use VAT (vertex animation texture) to make Houdini end on Houdini special effect (ue4/ue5)
- Your driver settings have been set to force 4x antialiasing in OpenGL applications
- Google Earth Engine(GEE)——evaluate实现一键批量下载研究区内的所有单张影像(上海市部分区域)
- Redis (II) distributed locks and redis cluster construction
- Solutions using protobuf in TS projects
- Is it safe to speculate in stocks by mobile phone?
猜你喜欢

一个五年北漂的技术er,根据这些年的真实经历,给应届生的一些建议

【论文阅读|深度】Role-based network embedding via structural features reconstruction with degree-regularized

Mqtt beginner level chapter

How to apply for a widget on wechat how to get a widget on wechat

The left sliding menu +menu item icon is grayed out

MCU development -- face recognition application based on esp32-cam

Flask博客实战 - 实现侧边栏最新文章及搜索

如何在Microsoft Exchange 2010中安装SSL证书

NETCORE performance troubleshooting

Basic use and cluster construction of consult
随机推荐
Houdini graphic notes: could not create OpenCL device of type (houdini_ocl_devicetype) problem solving
The title of my composition is - "my district head father"
Chinese translation of IMA Lazarus' the new giant, the goddess of Liberty
I hope to explain the basics of canvas as clearly as possible according to my ideas
什么是 CRA
Redis (I) principle and basic use
好好思考
View. post VS Handler. Differences and usage scenarios of post
【RPC】I/O模型——BIO、NIO、AIO及NIO的Rector模式
【动态规划】—— 数字三角形
[paper reading | deep reading] drne:deep recursive network embedding with regular equivalence
Is it safe to open an account with Guangzhou securities by mobile phone?
JS【中高级】部分的知识点我帮你们总结好了
Flask博客实战 - 实现侧边栏最新文章及搜索
IdentityServer4 定义概念
性能之网络篇
How do wechat applets make their own programs? How to make small programs on wechat?
Oracle查询自带JDK版本
Detailed explanation of Android interview notes handler
Create menu file