当前位置:网站首页>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>
边栏推荐
- 性能之网络篇
- Detailed explanation of Android interview notes handler
- 【系统分析师之路】第六章 复盘需求工程(综合知识概念)
- 一个五年北漂的技术er,根据这些年的真实经历,给应届生的一些建议
- 炒股票开户的话,手机开户安全吗?有谁知道啊?
- Mongodb's principle, basic use, clustering and partitioned clustering
- 之前字符串反转的题目
- Handler asynchronous message processing
- Webapi performance optimization
- WPF prism framework
猜你喜欢
无心剑中译伊玛·拉扎罗斯《新巨人·自由女神》
【论文阅读|深读】DRNE:Deep Recursive Network Embedding with Regular Equivalence
Flask博客实战 - 实现侧边栏最新文章及搜索
Linked list delete nodes in the linked list
Your driver settings have been set to force 4x antialiasing in OpenGL applications
【OpenCV 例程200篇】210. 绘制直线也会有这么多坑?
Mongodb's principle, basic use, clustering and partitioned clustering
[200 opencv routines] 210 Are there so many holes in drawing a straight line?
How do wechat sell small commodity programs do? How to open wechat apps to sell things?
Flask blog practice - archiving and labeling of sidebar articles
随机推荐
[today in history] June 24: Netease was established; The first consumer electronics exhibition was held; The first webcast in the world
Summary of considerations for native applet development
Performance network
[image fusion] image fusion based on morphological analysis and sparse representation with matlab code
Growth: how to think deeply and learn
我希望按照我的思路尽可能将canvas基础讲明白
tokenizers>=0.11.1,!= 0.11.3,<0.13 is required for a normal functioning of this module,
tokenizers>=0.11.1,!=0.11.3,<0.13 is required for a normal functioning of this module,
How do wechat sell small commodity programs do? How to open wechat apps to sell things?
Es learning
Kotlin arrays and collections (1) {create arrays, use arrays, use for in loops to traverse arrays, use array indexes, and multi-dimensional arrays}
The left sliding menu +menu item icon is grayed out
I'm afraid of the goose factory!
View. post VS Handler. Differences and usage scenarios of post
How to make small programs on wechat? How to make small programs on wechat
虚幻引擎图文笔记:使用VAT(Vertex Aniamtion Texture)制作破碎特效(Houdini,UE4/UE5)上 Houdini端
性能之文件系统篇
keep-alive
有关计网的五种类型题
[200 opencv routines] 210 Are there so many holes in drawing a straight line?