当前位置:网站首页>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>
边栏推荐
- [200 opencv routines] 210 Are there so many holes in drawing a straight line?
- Comparison and evaluation of digicert and globalsign single domain ov SSL certificates
- 学会自学【学会学习本身,比学什么都重要】
- What is CRA
- Shardingsphere proxy 4.1 sub database and sub table
- How to apply for a widget on wechat how to get a widget on wechat
- Flask blog practice - realize the latest articles and search in the sidebar
- Create menu file
- 单片机进阶---PCB开发之照葫芦画瓢(二)
- Your driver settings have been set to force 4x antialiasing in OpenGL applications
猜你喜欢
![[200 opencv routines] 210 Are there so many holes in drawing a straight line?](/img/1e/5b8245eb1c391649c7b2783c62c2b0.png)
[200 opencv routines] 210 Are there so many holes in drawing a straight line?

Free applet making tool, how to make wechat applet

How to build a wechat applet? How to open an applet?

OpenCV学习(二)---树莓派上安装opencv

P2P network core technology: Gossip protocol

Detailed explanation of Android interview notes handler

Your driver settings have been set to force 4x antialiasing in OpenGL applications

Flask博客实战 - 实现侧边栏文章归档及标签

ShardingSphere-Proxy 4.1 分庫分錶

【OpenCV 例程200篇】210. 绘制直线也会有这么多坑?
随机推荐
Flask博客实战 - 实现个人中心及权限管理
《天天数学》连载52:二月二十日
新学派:不诈骗经济学
[200 opencv routines] 210 Are there so many holes in drawing a straight line?
Basic use and principle of Minio
How to make a self-service order wechat applet? How to do the wechat order applet? visual editing
Flask blog practice - archiving and labeling of sidebar articles
WPF prism framework
Flask博客实战 - 实现侧边栏最新文章及搜索
一个五年北漂的技术er,根据这些年的真实经历,给应届生的一些建议
[paper reading | deep reading] line: large scale information network embedding
How to make small programs on wechat? How to make small programs on wechat
Chinese translation of IMA Lazarus' the new giant, the goddess of Liberty
Flask blog practice - realize the latest articles and search in the sidebar
How to develop wechat applet? How to open a wechat store
手机办理广州证券开户靠谱安全吗?
Redis (II) distributed locks and redis cluster construction
Google Earth Engine (Gee) - evaluate réalise le téléchargement en un clic de toutes les images individuelles dans la zone d'étude (certaines parties de Shanghai)
P2P network core technology: Gossip protocol
成长:如何深度思考与学习