situation

A common scenario,

Home -> Forward List page -> Forward Details page, Details page -> Back home -> Back List page

We hope,

From the details page –> return to the list page when the page is cached, do not request data again, improve user experience.

From the list page –> return to the home page, log out of the list page to get the latest data when entering different list pages.

task

Today let’s implement this requirement.

There is never more than one way to solve a problem in the code world.

For example, to find a value index from an array:

This can be done using the most basic for loop, tool functions like indexOf, or more semantically advanced functions like findIndex forEach.

I referred to a large number of articles, climbed the official documents, after finding several ways, let’s analyze one by one.

Let’s begin. 🙌

  1. Get rid of the person who needs it

    😂 emm… Maybe the code is more controllable than our lives.

    Programmers live in a realm of their own imagination

    As soon as I got in touch with computers, I found that computers are far less complicated than people. If you write good programs, you can get on with the computer and tell it to do what you want. This is when you are completely in charge. Every time you sit in front of your computer, you are walking through your kingdom, and the days are heavenly. The computer world is big, and programmers live in their own imaginary kingdom. You can imagine things in a computer down to every byte, every bit.

    — Lei Jun (yes, that’s Xiaomi Lei Jun)

    I agree with Lei Jun.

    It’s rare to find something in life that you love, and if you love code and you focus on it,

    One day,

    It comes back to you in all sorts of ways: wages, recognition, a sense of accomplishment, people who progress with you, people who resonate with you.

    If you bloom, butterflies will come. You mutual mian (can cheat a believe, less a sand sculpture and I rob sister 🤣)

  1. Sleepwear to people who need it

    😂 emm… , looking at the face in the mirror, this life should not be able to get any convenience from the face…

  1. keep-alive

    Keep-alive is an abstract component provided by Vue that is mainly used to preserve component state or avoid re-rendering.

    But keep-Alive caches all of its wrapped components.

action

We break down the requirements into 2 steps to implement them

1. Separate view components that need caching from those that don’t

The idea is as follows:

  1. Write tworouter-viewexit
<keep-alive>
    <! -- View components that need caching -->
  <router-view v-if="$route.meta.keepAlive">
  </router-view>
</keep-alive>

<! -- View component without cache -->
<router-view v-if=! "" $route.meta.keepAlive">
</router-view>
Copy the code
  1. inRouterTo define the view components that need to be cached
new Router({
    routes: [{path: '/'.name: 'index'.component: (a)= > import('./views/keep-alive/index.vue'),
            meta: {
                deepth: 0.5}}, {path: '/list'.name: 'list'.component: (a)= > import('./views/keep-alive/list.vue'),
            meta: {
                deepth: 1
                keepAlive: true // Need to be cached}}, {path: '/detail'.name: 'detail'.component: (a)= > import('./views/keep-alive/detail.vue'),
            meta: {
                deepth: 2}}}])Copy the code

2. According to the need to keep alive

We started with the API provided in the official documentation,

If the keep-alive component is included, only the components that match the include will be cached.

So the idea is to dynamically modify the include array for on-demand caching.

<keep-alive :include="include">
    <! -- View components that need caching -->
  <router-view v-if="$route.meta.keepAlive">
  </router-view>
</keep-alive>

<! -- View component without cache -->
<router-view v-if=! "" $route.meta.keepAlive">
</router-view>
Copy the code

Let’s listen for route changes in app.vue,

export default {
  name: "app".data: (a)= > ({
    include: []}),watch: {
    $route(to, from) {
      // If the page to be entered requires a keepAlive cache, push the name into the include array
      if (to.meta.keepAlive) {
        !this.include.includes(to.name) && this.include.push(to.name);
      }
      // If the page to form from is keepAlive cached,
      // Go back or forward according to deepth
      // If it is a backstep
      if (from.meta.keepAlive && to.meta.deepth < from.meta.deepth) {
        var index = this.include.indexOf(from.name); index ! = =- 1 && this.include.splice(index, 1); }}}};Copy the code

One thing to note

keep-alive

The push and splice in our code above are the name of the router.

Set the route name property to the same name as the route component.

result

Let’s verify our results

In vue-devtool, the gray components represent the cached state components. Notice how the list changes.

Write in the last

  1. Achieve on-demandkeep-alive, there are methods on the Internet, through modificationrouteIn the configurationmetaIn thekeepAliveValue to implement.

If you change the value of the meta directly, you may see the above situation. Keep-alive has a cached list, and normal Rotuer-view also has a cached list.

It takes a long time to reproduce this problem, so those who are interested can go and climb the pit themselves.

  1. Another option is to destroy the keep-alive view component by calling this.$destory() when it exits rotuer. This will cause the component to not be cached. This bug is mentioned in the official issue.

The resources

The official issue

Vue project global configuration page cache, to achieve on-demand read cache

About the animation

Thank you for your likes and replies. I’m sure many people want to share the demo source code here.

Because my company does not have the project of VUE to give full play to me. When I was writing the demo, I wasn’t thinking about encapsulation and optimization in animation,

So in the code in the shared demo, there will be a lot of duplicate code and ugly implementation in terms of animation. Forgive me

Source link

For some analysis of demo animations, see my first two articles