[Vuejs]-I'm losing content of the elements when I'm navigating by Vue Router

3👍

You can use <keep-alive>. Read more about it here

There are some disadvantages to this approach:

you lose lifecycle hooks like created, mounted, etc. since the
component is not being rebuilt from scratch anymore. You can replace
those lifecycle hooks with hooks that are specific to keep-alive
components

First approach

You can then specify which components to keep alive, by specifying

<keep-alive include="component1,component2">
  <router-view></router-view>
</keep-alive>

where those components need to have the matching name property:

name: 'component1'

Second approach

We can also use <keep-alive> with Route Meta Fields, where we have more granular control in the router on which components to keep alive (I’ve used the code from this codepen by Linusborg)

Router

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', 
      component: Home,
      meta: { keepAlive: false } 
    },
    { path: '/foo',
      component: Foo,
      meta: { keepAlive: true }
    }
  ]
})

Template

<transition name="fade" mode="out-in">
  <keep-alive v-if="$route.meta.keepAlive">
    <router-view></router-view>
  </keep-alive>

  <router-view v-else></router-view>
</transition>

Leave a comment