当前位置:网站首页>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>
边栏推荐
- How to do the wechat selling applet? How to apply for applets
- WPF prism framework
- How much does a wechat applet cost? Wechat applet development and production costs? Come and have a look
- Redis (II) distributed locks and redis cluster construction
- Google Earth Engine(GEE)——evaluate实现一键批量下载研究区内的所有单张影像(上海市部分区域)
- 原生小程序开发注意事项总结
- 虚幻引擎图文笔记:使用VAT(Vertex Aniamtion Texture)制作破碎特效(Houdini,UE4/UE5)上 Houdini端
- Network protocol learning -- lldp protocol learning
- QT: parsing JSON
- 【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
猜你喜欢

How to make small programs on wechat? How to make small programs on wechat

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

【图像融合】基于形态学分析结合稀疏表征实现图像融合附matlab代码

单片机开发---基于ESP32-CAM的人脸识别应用

【OpenCV 例程200篇】210. 绘制直线也会有这么多坑?

Webapi performance optimization

Request&Response有这一篇就够了

How to develop wechat applet? How to open a wechat store

Redis (II) distributed locks and redis cluster construction
![[paper reading | depth] role based network embedding via structural features reconstruction with degree regulated](/img/70/31a4eaec3f517089b220b35af2f3b7.png)
[paper reading | depth] role based network embedding via structural features reconstruction with degree regulated
随机推荐
WPF 绑定表达式和绑定数据源(一)
How do wechat sell small commodity programs do? How to open wechat apps to sell things?
Linked list delete nodes in the linked list
Android database security: after the user exits, the transaction rollback log still stores relevant data information
Houdini图文笔记:Your driver settings have been set to force 4x Antialiasing in OpenGL applications问题的解决
Houdini graphic notes: could not create OpenCL device of type (houdini_ocl_devicetype) problem solving
【OpenCV 例程200篇】210. 绘制直线也会有这么多坑?
输出式阅读法:把学到的知识用起来
Bitmap is converted into drawable and displayed on the screen
Floating window --- create a system floating window (can be dragged)
Google Earth engine (GEE) - evaluate enables one click batch download of all single images in the research area (some areas in Shanghai)
NETCORE performance troubleshooting
我希望按照我的思路盡可能將canvas基礎講明白
Yolov5 changing the upper sampling mode
DDS learning notes of opendds
How to make a self-service order wechat applet? How to do the wechat order applet? visual editing
宏的运用接续符\
XSS攻击
WPF prism framework
[paper reading | deep reading] line: large scale information network embedding