1. Configure the identifier (keepAlive: true) of the component that needs to be cached in the route. Set it to false first and then set it to true in the route guard

export default [
  {
    path: '/',
    component: () =>
      import(
        /* webpackChunkName: "mainContainer" */ '@/views/mainContainer/index.vue'
      ),
    children: [
      {
        path: 'list',
        meta: {
          keepAlive: true,
        },
        component: () =>
          import(
            /* webpackChunkName: "resource" */ '@/views/index.vue'
          ),
      },
    ],
  },
]

Copy the code

2. Add related code to app. vue

<div id="app"> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="! $route.meta.keepAlive"></router-view> </div>Copy the code

3. Use the Activated lifecycle hook function on cached components. That is, when the component is switched between keep-alive, that is activated

Check () {console.log(' yes I'm in the cache component ')},Copy the code

4. The business scenario, there is now A, B, C three pages, do some operation in B page, for example by entering search terms to search out the relevant data, A data, and then click to jump to C details page, click the back button, the C page B also after the search condition, in addition to B does not need to cache components, always is the latest state of the data, This can be distinguished by adding a type

$router.push({path:' B? Type =needToKeep'}) /* needToKeep is the identifier that needs to be cached */ A page to B page, this.$router.push({path:' B '}) B page: Check () {const {type} = this.$route.query console.log(' yes, I'm in the cache component ') if(type! =='needToKeep'){this.initdata() // needs to request data again}else{// If you want to refresh the page and request data again, arrange it! Const {type} = window. Performance. Navigation / / 1: refresh the page, 0: return to the page type = = = 1? this.initdata() : '' } },Copy the code

Conclusion: Keep-alive is a convenient function and easy to use. However, considering the business scenario, other people’s solution may not be suitable, and there will be some problems, so it is best to find a solution suitable for your own business