当前位置:网站首页>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>

原网站

版权声明
本文为[m0_ forty-nine million four hundred and seventy-one thousand si]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251014391393.html