vue implements page caching function

  • 2021-12-04 09:10:42
  • OfStack

This article example for everyone to share the vue page cache function of the specific code, for your reference, the specific content is as follows

Mainly use keep-alive to jump from the list page to the details page, and then click Back, the page cache does not need to request resources again.

1. Configure routing in router

Define whether the page needs caching in meta


import Vue from "vue";
import Router from "vue-router";

//  Avoid redundant navigation to the current location 
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router);
export default new Router({
  base: '',
  routes: [{
      path: "/",
      name: "index",
      component: () => import("@/layout"),
      redirect: '/login',
      children: [
        {
          path: 'dutySheet',
          name: 'dutySheet',
          component: () => import("@/pages/Dashboard/DutySheet")
        },
        {
          path: 'searchWord',
          name: 'searchWord',
          component: () => import("@/pages/dailyReportManage/searchWord/index"),
          meta: {
            keepAlive: true //  Pages need to be cached 
          }
        },
        //  Matching maintenance 
        {
          path: "troopAction",
          name: "troopAction",
          component: () => import("@/pages/Dashboard/TroopAction"),
          meta: {
            keepAlive: false//   No caching required 
          }
     },
      ]
    },
  ]
});

2. Configure APP. vue

Use keep-alive for caching


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

3. Just call the this. $router. back () method when you click the Return button


//  Return 
      bacKBnt(){
        this.$router.back()
      },

4. Clear the cache

Cached only for jumps to "exhibitionWord" or "exhibitionWeekWord" pages, not for jumps to other pages.


beforeRouteLeave(to, from, next) {
      if (to.name == 'exhibitionWord' || to.name == 'exhibitionWeekWord') { //  Routes that need to be cached name
          from.meta.keepAlive = true
          next()
        }else{
          from.meta.keepAlive = false
          next()
      }
    },

Related articles: