Detailed explanation of keepAlive use cases in Vue

Detailed explanation of keepAlive use cases in Vue

In development, it is often necessary to cache the status of the list page (such as scroll position information) when jumping from the list to the details page, and then returning to the details page. At this time, it is necessary to save the status and cache the status; Vue provides a keep-alive component for caching the status.
There are several solutions to the problem:

1. Use meta tags

1. First, record the keepAlive attribute as true in the meta tag in the route

path: '/classify',
  name: 'classify',
  component: () => import('@/views/classify/classify.vue'),
  meta: {
    title: 'Leishitao coupons',
    keepAlive: true
  }
},

2. Add the scrollBehavior method when creating a router instance

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. Wrap the keep-alive component on the router-view component that needs to be cached

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

4. Since caching is required in some cases and not in others, you can make a judgment in the routing hook function in the cached component

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 component caching, but this method has bugs. First, it is not cached when the page is opened for the first time, that is, the first time you jump from the list page to the detail page, there is no cache when you come back. It will be cached when you enter the detail page later, and only the state of the first entry will be cached, and the data will not be requested again. If you select a category on page A and jump to page B, and then jump from the B list page to the detail page, this state will be cached at this time, and it will not be cached again when you jump from other categories on page A to page B in the future, so that each time you return to page B from the detail page, you will jump to the state of the first cache; if your project has only one state that needs to be cached, you can consider using this method

2. Use include, exclude attributes and beforeRouteEnter hook function

First, let me introduce include and exclude Vue documentation https://cn.vuejs.org/v2/api/#keep-alive
It is a new attribute added after vue2.0
include is the component that needs to be cached;
Exclude means that all components except some are cached;
The include and exclude attributes allow components to be conditionally cached. Both can be expressed as a comma-delimited string, a regular expression, or an array:

<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
 
<!-- Regular expression (using `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
 
<!-- Array (using `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

The match is first checked against the component's own name option. If the name option is not available, it is matched against its local registered name (the key value of the parent component's components option). Anonymous components cannot be matched.

max is only added in 2.5.0, which is the maximum number of component instances that can be cached. Once this number is reached, the cached component instance that has not been accessed in the longest time will be destroyed before a new instance is created.

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

activated and deactivated.

Briefly introduce that in the components/routes included in keep-alive, there will be two more life cycle hooks: activated and deactivated.
Documentation: In 2.2.0 and higher, activated and deactivated will be triggered in all nested components in the tree.
activated is called when the component is first rendered, and then called each time the cached component is activated.
Activated call time:
The first time you enter a cached route/component, after mounted, before the beforeRouteEnter guard is called before the callback function passed to next:

beforeMount=> If you come from another route/component (component destroyed/or deactivated when leaving the cache)=>mounted=> activated Enter the cache component=> execute the beforeRouteEnter callback

Because the component is cached, these hooks will not be triggered when entering the cache route/component again: // beforeCreate created beforeMount mounted will not be triggered.

deactivated: When the component is deactivated (leaves the route), if keep-alive is used, beforeDestroy (the hook before component destruction) and destroyed (component destruction) will not be called, because the component is not destroyed but cached.
This hook can be seen as a replacement for beforeDestroy. If you cache a component and want to do something when the component is destroyed, you can put it in this hook.
If you leave the route, it will trigger in sequence:

Leave the current route hook in the component beforeRouteLeave => route front guard beforeEach => global post hook afterEach => deactivated Leave the cache component => activated Enter the cache component (if you enter the cache route

How to use cache in the project:
1. Add the scrollBehavior method to the created router object, as above;
2. Add the components that need to be cached to the include attribute

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

3. In the next callback function of beforeRouteEnter, initialize the situation where the A page does not need to be cached, that is, write the things that should be written in create here; pay attention to write all the data that needs to be initialized again, otherwise there will be bugs; so it is not recommended

beforeRouteEnter (to, from, next) {
    next(vm => {
      // Access component instance through `vm` if (from.path !== '/goods_detail') { // Must be refreshed when entering page B from A vm.titleText = vm.$route.query.name
        vm.categoryUpper = vm.$route.query.categoryUpper
        vm.goods = []
        vm.page = 1
        vm.catsIndex = 0
        vm.is_search = false
        vm.getCats2()// is the various types originally written in create}
    })
  }

3. Use include, exclude attributes and beforeRouteLeave hook function and vuex (recommended)

The third method is similar to the second method, except that the components that need to be cached are saved in global variables, and you can flexibly control which components need to be cached and which do not in the routing hook function; compared with the second method, there is no need to reinitialize the data every time, but the data needs to be saved in vuex;
On the code
1. Add the scrollBehavior method to the created router object, as above;
2. Add the components that need to be cached to the include attribute

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

3. Add the variable name of the component to be cached and the corresponding method in the store;

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

4. Control the components that need to be cached in the beforeRouteLeave hook function

beforeRouteLeave (to, from, next) { //To control the components that need to be cached when leaving the component, otherwise the first time of not caching will occur this.busy = true
    if (to.path === '/goods_detail') { // Components need to be cached when going to the details page, and no caching is required in other cases this.$store.commit('GET_CATCHE_COMPONENTS', ['home'])
    } else {
      this.$store.commit('GET_CATCHE_COMPONENTS', [])
    }
    next()
  },

In addition, in our project, we encountered the problem that components were reused and not updated when the routes were the same but the parameters were different. Vue officially gave a response to route parameter changes

watch:
    '$route' (to, from) {
      document.title = this.$route.query.name
      this.getDefault() //respond according to parameter data}

  },

This is the end of this article about the detailed use of keepAlive in vue. For more relevant content on the use of keepAlive in vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Instructions for using keepAlive in Vue projects (super practical version)
  • Detailed explanation of keepAlive usage in Vue front-end development
  • Detailed explanation of vue keepAlive cache clearing problem case
  • Detailed explanation of the function and usage of keepAlive component in Vue
  • Solve the problem of not caching when using keepAlive in Vue
  • Vue keepsAlive setting does not take effect and its solution

<<:  How to delete a MySQL table

>>:  How to decrypt Linux version information

Recommend

Mysql implements three functions for field splicing

When exporting data to operations, it is inevitab...

How to quickly build your own server detailed tutorial (Java environment)

1. Purchase of Server 1. I chose Alibaba Cloud...

Reasons and methods for Waiting for table metadata lock in MySQL

When MySQL performs DDL operations such as alter ...

Detailed explanation of Vue's calculated properties

1. What is a calculated attribute? In plain words...

How to install PHP7.4 and Nginx on Centos

Prepare 1. Download the required installation pac...

Summary of xhtml block level tags

* address - address * blockquote - block quote * c...

A nice html printing code supports page turning

ylbtech_html_print HTML print code, support page t...

How does Vue implement communication between components?

Table of contents 1. Communication between father...

Docker installation and configuration command code examples

Docker installation Install dependency packages s...

Repair solution for inconsistent MySQL GTID master and slave

Table of contents Solution 1: Rebuild Replicas Pr...

How to point the target link of a tag to iframe

Copy code The code is as follows: <iframe id=&...

CSS realizes the mask effect when the mouse moves to the image

1. Put the mask layer HTML code and the picture i...

Solution to forgetting the MYSQL database password under MAC

Quick solution for forgetting MYSQL database pass...

A brief analysis of the difference between ref and toRef in Vue3

1. ref is copied, the view will be updated If you...