vue keepAlive in use

In development often state (such as scroll position information) needs to be cached list page jump to details page from the list, and then return to the details page of time, this time on the need to save the state, to the state of the cache; vue in providing a keep-alive components used to cache the state.
You can solve the problem by following the program;

First, the use of meta tags

1, the first recorded in the meta tag routing attribute to true keepAlive

  path: '/classify',
    name: 'classify',
    component: () => import('@/views/classify/classify.vue'),
    meta: {
      title: '雷石淘券券',
      keepAlive: true
    }
  },

2, when creating router instance method plus scrollBehavior

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  }
})

3 / keep-alive package assembly needs to be cached in the router-view assembly  

<keep-alive>
   <router-view v-if='$route.meta.keepAlive'></router-view>
</keep-alive>
<router-view v-if='!$route.meta.keepAlive'></router-view>

4, since in some cases need to be buffered in some cases do not need cache, the cache determination can be done in the routing of the assembly of the hook function  

beforeRouteLeave (to, from, next) {
    this.loading = true
    if (to.path === '/goods_detail') {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
     // this.$destroy()
    }
    next()
  },

It can support cache component, but this method has a bug, first of all, when you first open the page does not cache that first jump page detail page from the list, and then come back and not cached, behind only enter the details page cached
and only cache for the first time to enter the state, will not be re-request data, if selected as a Category a page B page jump, then jump to the details page from the B list page, then caches this state, and later and then jump to the page from another classification B a page will not be cached again, so that each time you return will jump from page B details page for the first time the cache state; when your project requires only one state cache can be considered using this method

 

Second use include, exclude hook function attributes and beforeRouteEnter

First, tell us about the include and exclude vue documents https://cn.vuejs.org/v2/api/#keep-alive
was after vue2.0 new properties
include a component that needs to be cached;
the exclude that in addition to certain components buffer;
the include and exclude attributes allow conditional assembly buffers. Both strings are separated by commas, or a regular expression to represent the array:

<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>

<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

First check the matching component itself name option, if the name option is not available, matching its locally registered name (parent component key components option). Anonymous component can not be matched.

max 2.5.0 only add up to the number of component instances can be cached. Once this figure reached before the new instance is created, the oldest instance of the component has not been accessed cache will be destroyed out.

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

 

activated 与 deactivated。

Brief in the component / route included in the keep-alive, will be more than two hooks life cycle: activated and deactivated.
Documentation: In version 2.2.0 and later in, activated and deactivated at will trigger all nested components within the tree.
activated will be called when the component is first rendered and then called each time the cache component is activated.
activated call opportunity:
for the first time into the cache routing / components, in the back mounted, beforeRouteEnter guard passed to the next callback function before the call:

beforeMount => If you are coming (assembly destroy destroyed / or leave the cache deactivated) => mounted => from other routing / components activated into the cache component => callback execution beforeRouteEnter

Because components are cached, re-enter the routing cache / components, it does not trigger these hooks: // beforeCreate created beforeMount mounted will not trigger.

deactivated: Called when the component is disabled (left routing)
using a keep-alive will not be called beforeDestroy (before the destruction of the component hook) and destroyed (destruction of components), because the components are not destroyed, cached up.
The hook can be seen as an alternative beforeDestroy, if you cache components, to do something at the time of the destruction of the components, you can put the hook in.
If you leave the route, will in turn trigger:

Leaving the current routing hook beforeRouteLeave => Routing front guard beforeEach => Global rear hook afterEach => deactivated leave the cache component => activated into the cache component (if you enter is cached in the routing components


 

Project cache to use:
1, the object is created on the router plus scrollBehavior method, supra;
2, will need to cache components added to include properties in the

<keep-alive :include="['home','classify','search']">
      <router-view></router-view>
</keep-alive>

3, in the next beforeRouteEnter back off function, the situation does not need to return to A page cache initialization, coming originally created in the need to write something to write here; be sure to pay attention to all the data required to initialize to write again, otherwise there will be bug; it is not recommended  

beforeRouteEnter (to, from, Next) { 
    Next (VM => { 
      // `vm` by accessing component instance 
      if (from.path! == '/ goods_detail ') {// must be fed from A to B until the page refreshes 
        VM = vm.titleText. $ route.query.name 
        vm.categoryUpper = VM. $ route.query.categoryUpper 
        vm.goods = [] 
        vm.page. 1 = 
        vm.catsIndex = 0 
        vm.is_search to false = 
        vm.getCats2 () // was originally written in various created inside 
      } 
    }) 
  }

 

Third, the use include, exclude property and beforeRouteLeave hook function and vuex (recommended)

The third method and the second similar, different places that will save the need to cache components to global variables, which components can be flexibly controlled routing hook functions that will cache that do not require cache; with the second method , do not require re-initialized every time data, but the data needs to be saved in the vuex;
on the code
1, the object created on router plus scrollBehavior method, supra;
2, the cache will need to include components added properties in the

<keep-alive :include="catch_components">
      <router-view></router-view>
</keep-alive>

3, the variable name in the addition of required cache store in the component, and a corresponding method;

export default new Vuex.Store({
  state: {
    catch_components: []
  },
mutations:{
    GET_CATCHE_COMPONENTS (state, data) {
      state.catch_components = data
    }
}
})

4, the control assembly beforeRouteLeave hook function required in the cache  

beforeRouteLeave (to, from, next) {// To control assembly needs to be cached when leaving the assembly, otherwise the case where the first cache will not appear 
    this.busy to true = 
    IF (to.path === '/ goods_detail ') {// when destined to cache page before assembly, in other cases do not need to cache 
      the this. store.commit $ (' GET_CATCHE_COMPONENTS ', [' Home ']) 
    } {the else 
      the this. store.commit $ (' GET_CATCHE_COMPONENTS ', []) 
    } 
    Next () 
  },

In addition, a problem routing the same situation but with different parameters of the components are multiplexed, is not updated in our project, vue official gives the  response routing parameters

Watch: { 
    '$ route' (to, from) { 
      document.title the this $ = route.query.name. 
      this.getDefault () // The parameter data in response 
    } 

  },

  

  

  

  

  

  

  

Guess you like

Origin www.cnblogs.com/mary-123/p/11248178.html